I have an array of objects, which has an array of objects inside (it also has another one inside).
const array = [
{
id: 1,
prod: [
{
id: 1,
op: [
{
id: 1
},
{
id: 2
}
]
},
{
id: 2,
op: [
{
id: 1
}
]
}
]
},
{
id: 2,
prod: [
{
id: 1,
op: [
{
id: 1
},
{
id: 2
}
]
},
{
id: 2,
op: [
{
id: 1
}
]
}
]
}
];
The question is how to enter a new key value in each one so that it looks like this:
[
{
id: 1,
isChecked: false,
prod: [
{
id: 1,
isChecked: false,
op: [
{
id: 1,
isChecked: false
},
{
id: 2,
isChecked: false
}
]
},
{
id: 2,
isChecked: false,
op: [
{
id: 1,
isChecked: false
}
]
}
]
},
{
id: 2,
isChecked: false,
prod: [
{
id: 1,
isChecked: false,
op: [
{
id: 1,
isChecked: false
},
{
id: 2,
isChecked: false
}
]
},
{
id: 2,
isChecked: false,
op: [
{
id: 1,
isChecked: false
}
]
}
]
}
];
I know that iterating can be achieved
array.map(object => {
return {
...object,
isChecked: false
}
})
but is there a better way to do it?
some way that all objects have that key/value without iterating multiple times
2
Answers
You can do it recursively regardless of the number and names of the array properties. The only problem you should insert the
isChecked
afterid
so we should do that explicitly.Note that we don’t use
Object.XXX
methods and spread syntax here, because they are slow.You can do it recursively with a one-liner like this:
It adds
isChecked = false
only for regular (non-array) objects, and recurses for all items in the object (which will include both object property values and array elements).