I need to iterate this json and push the values into an other array
[
{
"id": 1,
"nombre": "Samson",
"marcaModelo": [
{
"id": 6,
"nombre": "API 6D "
}
]
}
{
"id": 6,
"nombre": "Endress + Hauser",
"marcaModelo": [
{
"id": 10,
"nombre": "Proline t-mass 65F50-AK2AH1RCBBCA"
},
{
"id": 8,
"nombre": "Cerabar M"
}
]
}
]
I made out with this
Object.entries(res).forEach((value, key) => {
console.log(key, value)
this.marcas.push({
'marcaId': res[key].id,
'marcaNombre': res[key].nombre,
'modeloId': res[key].marcaModelo[0].id,
'modeloNombre': res[key].marcaModelo[0].nombre
})
console.log(this.marcas)
})
but only push one marcaModelo object into marcas array, if I replace marcaModelo[0] for marcaModelo[key] I get an undefined.
I need something like this
{
marcaId:6
marcaNombre:"Endress + Hauser"
modeloId:[10, 8]
modeloNombre:[Proline t-mass 65F50-AK2AH1RCBBCA, Cerabar M]
}
You need a nested loop for all the marcaModelo objects; you can use .map() to return an array of the results of a function on each element.. It also doesn't seem like you need to use Object.entries(). The original object is an array, you can use .forEach() directly on it.
res.forEach(value => {
console.log(value);
this.marcas.push({
'marcaId': value.id,
'marcaNombre': value.nombre,
'modeloId': value.marcaModelo.map(o => o.id),
'modeloNombre': value.marcaModelo.map(o => o.nombre)
});
console.log(this.marcas);
}
or
res.map(({ id, nombre, marcaModelo }) => ({
marcaId: id,
marcaNombre: nombre,
modeloId: marcaModelo.map(m => m.id),
modeloNombre: marcaModelo.map(m => m.nombre),
}));
Related
I'm stuck on this type of situation where the values of the object is changed to a different value. Is there way to shift a value to a key or would simply deleting and adding be better? I tried to loop to see which of the keys overlap in value and using the if statement and conditions i tried adding or deleting using Array methods. However, since the inter data is an object i am sruggling to find the right methods or even the process. I also tried using a function to insert the data and pushing to a new empty array that is returned from the function.
If I have objects in an array like so:
const data = [
{
"date": "12/22",
"treatment": "nausea",
"count": 2
},
{
"date": "12/23",
"treatment": "cold",
"count": 3
},
{
"date": "12/22",
"treatment": "cold",
"count": 2
}
];
and wanting to change the data like so:
const newData = [
{
"date": "12/22",
"cold": 2
"nausea": 2,
},
{
"date": "12/23",
"cold": 3
}
];
try this code using loop and reduce and every time add to new array
const data = [
{
"date": "12/22",
"treatment": "nausea",
"count": 2
},
{
"date": "12/23",
"treatment": "cold",
"count": 3
},
{
"date": "12/22",
"treatment": "cold",
"count": 2
}
];
const newData = [];
const dataByDate = data.reduce((acc, curr) => {
if (!acc[curr.date]) {
acc[curr.date] = { date: curr.date };
}
acc[curr.date][curr.treatment] = curr.count;
return acc;
}, {});
for (let date in dataByDate) {
newData.push(dataByDate[date]);
}
console.log(newData);
We want to reduce the data by unique dates. This can be done with:
An object as a dictionary,
Set or Map, or
Some other custom implementation.
Prefer to use Array.reduce() when reducing an array. This is standardized and more expressive than a custom implementation.
Using a map-like structure as the accumulator allows reduction of the dates by uniqueness and the data itself, simultaneously.
Note: Properties of objects are converted to Strings (except for Symbols). So if you want to use different "keys" that are equal after conversion (e.g. 0 and "0"), you cannot use objects; use Map instead.
(All our dates are Strings already, so this warning does not apply here.)
When using an object we can use the nullish coalescing assignment ??=: This allows us to assign an initial "empty" entry ({ date: dataEntry.date }) when encountering a new unique date.
Further, that assignment evaluates to the dictionary's entry; the entry that was either already present or just assigned.
Then we only need to assign the treatment and its count as a key-value pair to the entry.
const data = [
{ "date": "12/22", "treatment": "nausea", "count": 2 },
{ "date": "12/23", "treatment": "cold", "count": 3 },
{ "date": "12/22", "treatment": "cold", "count": 2 }
];
const newData = reduceByDate(data);
console.log(newData);
function reduceByDate(data) {
const dataByDate = data.reduce((dict, dataEntry) => {
const dictEntry = dict[dataEntry.date] // Get existing or ...
??= { date: dataEntry.date }; // ... just initialized entry.
dictEntry[dataEntry.treatment] = dataEntry.count;
return dict;
}, {});
// Transform dictionary to array of reduced entries
return Object.values(dataByDate);
}
You can make use of reduce() and Object.assign().
First we use reduce to combine objects with the same date into one object and then use assign to merge the values:
const data = [{
"date": "12/22",
"treatment": "nausea",
"count": 2
},
{
"date": "12/23",
"treatment": "cold",
"count": 3
},
{
"date": "12/22",
"treatment": "cold",
"count": 2
}
];
const newData = data.reduce((acc, curr) => {
const dateIndex = acc.findIndex(item => item.date === curr.date);
if (dateIndex === -1) {
acc.push({
date: curr.date,
[curr.treatment]: curr.count
});
} else {
acc[dateIndex] = Object.assign({}, acc[dateIndex], {
[curr.treatment]: curr.count
});
}
return acc;
}, []);
console.log(newData)
I am building a Blog app and I am trying to get results but it is showing duplicate results, I am trying to remove the duplicate results from the array.
But the problem is there are two key and values in each dict inside array, One is unique and other can be same so I am trying to distinct based on same array, It worked But the other key and value pair (which is unique) is not attaching with the other pair.
response which is returning from db
[
{
"id": 2,
"name": "user_1"
},
{
"id": 3,
"name": "user_3"
},
{
"id": 4,
"name": "user_3"
}
]
App.js
function App() {
const [blogs, setBlogs] = useState([]);
axios.get("retract_blogs/").then((res) => {
// Here I also want to attach "id"
setBlogs({[...new Set(res.data.data.map(x => x.name))]})
}
return(
<div>
{
blogs.map((user) =>
<div>
{user.name}
// Here I wamt to show ID
// {user.id}
</div>
}
</div>
)
}
I want to add id with x.username, I also tried using
setBlogs({data:[...new Set(res.data.data.map(x => x.name, x.id))]})
But it showed
x is not defined
But I am trying to add both name and id, and remove duplicates based on name not id.
I have tried many times but it is still not working.
To keep the id of the last occurence you can create a Map of the array keyed by name and then convert back to an array using the iterator returned by Map.values(). This works by overwriting earlier entries in the Map with the same name.
const users = [{ "id": 2, "name": "user_1" }, { "id": 3, "name": "user_3" }, { "id": 4, "name": "user_3" }];
const result = [...new Map(users.map((user) => [user.name, user])).values()];
console.log(result);
// [ { id: 2, name: 'user_1' }, { id: 4, name: 'user_3' } ]
If you instead want to keep the id of the first occurence of a name you can use a slightly modified 'group by' grouping into an object by name (here in a reduce() call, but it could easily be done in a standard loop as well) before taking the Object.values. This works by only setting the accumulator[name] property if it doesn't already exist, here using logical nullish assignment (??=)
const users = [{ "id": 2, "name": "user_1" }, { "id": 3, "name": "user_3" }, { "id": 4, "name": "user_3" }];
const result = Object.values(users.reduce((a, c) => (a[c.name] ??= c, a), {}));
console.log(result);
// [ { id: 2, name: 'user_1' }, { id: 3, name: 'user_3' } ]
Actually I'm trying to get all the value of object1 and get true if Like object has some id that match with current user id
Array [
Object {
"id": "-MgFbI5wXjtjKln1Wkqe",
"like": Object {
"-MgpHytKWNplejaxtLLF": "-MgpHytKWNplejaxtLLF",
},
"likes_count": 7,
},
Object {
"id": "-MgpHytKWNplejaxtLLF",
"like": Object {
"-MgFbI5wXjtjKln1Wkqe": "aC9dL88GCAXdnGyefY1XDiXd7Iu1",
},
"likes_count": 0,
},
]
Here is my code, arr contains whole object that are given above
const us = arr.map((item) => {
return item.like;
});
const ik = us.includes(uid);
console.log("snap ", ik);
I want given below object that include like variable true if like object have user id otherwise it assign false
Array [
Object {
"id": "-MgFbI5wXjtjKln1Wkqe",
"like":false,
"likes_count": 7,
},
Object {
"id": "-MgpHytKWNplejaxtLLF",
"like":true,
"likes_count": 0,
},
]
const us =Array(); // us is the final table that you need
for(i=0;i<arr.length;i++){
us[i]= {
"id":arr[i].id,
"like": arr[i].like===uid?true:false,
"likes_count": arr[i].likes_count,
}
}
or this :
const us = Array();// us is the final table that you need
arr.forEach((element,index) => us[index] = {
"id":arr[index].id,
"like": arr[index].like===uid?true:false,
"likes_count": arr[index].likes_count,} );
I have an array like this:
[
{
"id": 10002,
"flag": false,
"list": [
"aaa",
"bbb"
]
},
{
"id": 10001,
"flag": true,
"list": [
"10002",
"10003"
]
},
{
"id": 10003,
"flag": false,
"list": [
"ccc",
"ddd"
]
}
]
i tried this
initially i have "10001" value so iterate this array to take "list" array if flag==true then stored into newarray. but its not working.
I want it to be like this: [ "aaa", "bbb", "ccc", "ddd" ].
If i understand correctly this is what you want:
const someArray = [
{
"id": 10001,
"list": [
"10002",
"10003"
]
},
{
"id": 10002,
"list": [
"aaa",
"bbb"
]
},
{
"id": 10003,
"list": [
"ccc",
"ddd"
]
}
];
const [head,...rest] = someArray;
const result = head.list.reduce((acc,currentId)=>acc.concat(rest.find(({id})=> id === parseInt(currentId)).list),[]);
Here is a jsFiddle https://jsfiddle.net/sudakatux/9hju85mt/22/
Explanation:
take the head and splitted from the rest since the head contains the ids.
using the head as a dictionary find each list for each id in the head and concatenate
note the id must be in the subsequent list else it will fail with undefined. if you want to account for this error you can set a defualt empty object with a list. for example this part:
rest.find(({id})=> id === parseInt(currentId)).list
Will look like
rest.find(({id})=> id === parseInt(currentId)) || {list:[]}).list
Which basically means if its undefined return an object that has an empty list so then it will concatenate an empty list which results in being the same list. (like multiplying by 1 in a multiplication)
Hope it helps.
EDIT after your edit.
If your array is in different order you need to find the dictonary and then the logic is the same
const [newHead] = otherArray.filter(({list}) => list.every(elem=>!isNaN(elem)));
const result2 = newHead.list.reduce(
(acc,currentId) =>acc.concat(otherArray.find(({id})=> id === parseInt(currentId)).list),[]);
if you are testing for the flag then your head filter would look like. the blocks are the same the only thing that changes is the condition.
const [newHead] = otherArray.filter(({flag}) => flag));
(note* that instead of using the rest i used the complete array(otherArray). since im targeting equality.
Im using filter and extracting the first element of the result. because im accounting for the possibility that in the future you may have more than one "dictionary element". if thats the case in the future then you just have to concat the lists from the filter result
const array = [
{
id: 10001,
flag: true,
list: ["10002", "10003"]
},
{
flag: false,
id: 10002,
list: ["aaa", "bbb"]
},
{
flag: false,
id: 10003,
list: ["ccc", "ddd"]
}
];
const isHead = item => item.flag && item.id === 10001;
const head = array.find(isHead);
const rest = array.filter(item => !isHead(item));
const result = rest
.flatMap(item =>
head.list.includes(item.id.toString()) && item.list
);
console.log(result);
You can map over the list of the first item and concat all the lists from those ids.
const mapItems = (input) => {
const source = input[0].list;
source.reduce((results, id) => {
return results.concat(input.find(item => item.id === id).list);
}, []);
};
mapItems([
{
"id": 10001,
"list": [
"10002",
"10003"
]
},
{
"id": 10002,
"list": [
"aaa",
"bbb"
]
},
{
"id": 10003,
"list": [
"ccc",
"ddd"
]
}
]);
You can fetch the values of the list of first object in the array as arr[0]['list']
Once you have these values (10002,10003) then you can fetch the list values of remaining objects in the array whose id key matches one of the above values.
if(arr[i]['id'] == 10002 || arr[i]['id'] == 10003){
//fetch the list values
}
I am trying to get a structure like
var tableData= [
['Hfbj'],
['Hygh'],
[6],
['mayur'],
[2563458952]
]
Here is my JSON data:
data:{
"address"': "Hfbj"
"id": 6
"landmark": "Hygh"
"name": "mayur"
"phone": 2563458952
"title": "aaa"
}
I am using react-native-table-component in which that type of structure needed. For that, I am doing the following but it showing data.map is not function and undefined.
let newdata = this.state.tableData[0].push(
[responseJson.data.title],
[responseJson.data.title]
);
this.setState({
tableData: newdata
});
How can I achieve it?
You could make use of Object.values and Array.map:
var reponseJson = {
data: {
"address": "Hfbj",
"id": 6,
"landmark": "Hygh",
"name": "mayur",
"phone": 2563458952,
"title": "aaa"
}
};
var newData = Object.values(reponseJson.data)
.map(item => [item]);
console.log(newData);
Note that I used the responseJson name to match your question, but as #Andreas pointed out, this is an object, not JSON.
If you need only certain columns (as requested in the comments below), use Object.keys and Array.filter on them before rebuilding the array:
var reponseJson = {
data: {
"address": "Hfbj",
"id": 6,
"landmark": "Hygh",
"name": "mayur",
"phone": 2563458952,
"title": "aaa"
}
};
var keysToKeep = ['address', 'landmark', 'title'];
var newData = Object.keys(reponseJson.data)
.filter(key => keysToKeep.includes(key))
.map(key => [reponseJson.data[key]]);
console.log(newData);
.map Is for arrays, whereas your responseJson.data is an Object. To get turn that Object into an array of its values you can do Object.values(responseJson.data)