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}))
asked Nov 15, 2021 at 1:41
Joseph
7,87533 gold badges107 silver badges235 bronze badges
3 Answers 3
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);
answered Nov 15, 2021 at 1:46
Andy
63.7k13 gold badges72 silver badges99 bronze badges
datas.reduce((acc, val) => {
return acc.concat(val.details)
}, [])
Comments
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);
answered Nov 15, 2021 at 2:10
DecPK
25.4k6 gold badges33 silver badges46 bronze badges
Comments
lang-js