I have a problem on combining arrays that I wanted to get that's coming from another array.
datas
datas = [
{
"id": "22333",
"name": "",
"details": [
{
"value": 1
},
{
"value": 2
}
]
},
{
"id": "4444",
"name": "",
"details": [
{
"value": 99
},
{
"value": 66
}
]
}
]
expected output
final = [
{
"value": 1
},
{
"value": 2
},
{
"value": 99
},
{
"value": 66
}
]
Code
datas.map((data) => ({ ...data.details}))
The
flatMapmethod returns a new array formed by applying a given callback function to each element of the array, and then flattening the result by one level. It is identical to amapfollowed by aflatof depth 1, but slightly more efficient than calling those two methods separately.
const datas=[{id:"22333",name:"",details:[{value:1},{value:2}]},{id:"4444",name:"",details:[{value:99},{value:66}]}];
const flattened = datas.flatMap(obj => obj.details);
console.log(flattened);
To get the actual numbers map over the details array.
const datas=[{id:"22333",name:"",details:[{value:1},{value:2}]},{id:"4444",name:"",details:[{value:99},{value:66}]}];
const flattened = datas.flatMap(obj => {
return obj.details.map(el => el.value);
});
console.log(flattened);
datas.reduce((acc, val) => {
return acc.concat(val.details)
}, [])
You can also make use of reduce here:
arr.reduce((acc, curr) => {
acc.push(...curr.details);
return acc;
}, [])
const arr = (datas = [
{
id: "22333",
name: "",
details: [
{
value: 1,
},
{
value: 2,
},
],
},
{
id: "4444",
name: "",
details: [
{
value: 99,
},
{
value: 66,
},
],
},
]);
const result = arr.reduce((acc, curr) => {
acc.push(...curr.details);
return acc;
}, []);
console.log(result);