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}))
CodePudding user response:
The
flatMap
method 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 amap
followed by aflat
of 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);
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
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);
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
CodePudding user response:
datas.reduce((acc, val) => {
return acc.concat(val.details)
}, [])
CodePudding user response:
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);
<iframe name="sif3" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>