Issue
I have this array of object, I want to extract its ids.
const arr = [
{
"id": "1",
},
{
"id": "2",
"options": [
{
"id": "2.1",
}
]
},
]
I did this
const one = arr.map(ob => ob.id)
const two = arr.flatMap(ob => ob.options).map(ob => ob?.id).filter(Boolean)
console.log([...one, ...two])
which worked fine, it prints ['1', '2', '2.1']
which is what I wanted but is there any simpler or shorter way to do it?
Solution
Here's one possible approach - .concat
onto an array of just the parent id
property inside the mapper callback.
const arr = [
{
"id": "1",
},
{
"id": "2",
"options": [
{
"id": "2.1",
}
]
},
];
const result = arr.flatMap(obj => [obj.id].concat(obj.options?.map(o => o.id) ?? []));
console.log(result);
Another is
const arr = [
{
"id": "1",
},
{
"id": "2",
"options": [
{
"id": "2.1",
}
]
},
];
const toId = obj => obj.id;
const result = arr.map(toId).concat(arr.flatMap(o => o.options?.map(toId) ?? []));
console.log(result);
Answered By - CertainPerformance
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.