I have nested objects within arrays that I need to manipulate.
{
"page": [
{
"num": "1",
"comp": [
{
"foo": "bar",
"bar": "foo",
"name": "comp1",
"items": [
{
"fooBar":"barFoo",
"itemData":
{
"foo": "bar",
"bar": "foo",
"fooBar": "barFor"
}
}
]
}
]
},
{
"num": "2",
"comp": [
{
"foo": "bar",
"bar": "foo",
"name": "comp2",
"items": [
{
"fooBar":"barFoo",
"itemData":
{
"foo": "bar",
"bar": "foo",
"fooBar": "barFor"
}
}
]
},
{
"items": [
{
"fooBar":"barFoo2",
"itemData":
{
"foo": "bar",
"bar": "foo",
"fooBar": "barFor"
}
},
{
"itemData":
{
"foo": "bar",
"bar": "foo",
"fooBar": "barFor"
}
}
]
}
]
},
{
"num”: "3”
}
]
}
My goal is to create a new array containing only the itemData
, while maintaining the structure of the original object.
To achieve this, I plan on using nested for loops to access the itemData
object:
for (const [i, page] of this.testingAnimation.pages.entries()){
for (const [j, comp] of page.comp.entries()){
for (const [k, item] of comp.items.entries()){
if (item.itemData !== undefined) {
} else {
}
}
}
}
Once I have extracted the itemData
, I need to insert it into a new array while preserving the original nested structure without any extra key-value pairs.
Expected Output:
{ "page": [ { "comp": [ { "items": [ { "itemData": { "foo": "bar", "bar": "foo", "fooBar": "barFor" }} ] }] }, { "comp": [ { "items": [{ "itemData": { "foo": "bar", "bar": "foo", "fooBar": "barFor" } }] }, { "items": [{ "itemData": { "foo": "bar", "bar": "foo", "fooBar": "barFor" } },{ "itemData": { "foo": "bar", "bar": "foo", "fooBar": "barFor" } }] }] }, { "num": "3” }] }