【发布时间】:2021-12-25 18:19:54
【问题描述】:
我在数组中有一个嵌套对象。
{
"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"
}
]
}
所以我要做的是用itemData 创建一个新数组,但保持对象的一般结构不变。
我不能只删除每个不需要的键/值,因为键可以更改或可以添加新键,并且很难维护。所以我在想一些嵌套的 for 循环来到达 itemData 对象:
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 {
}
}
}
}
但现在我有了itemData,我如何将它放入数组中,同时保留原始对象的一般嵌套结构,而无需额外的键/值
预期输出:
{
"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"
}
]
}
【问题讨论】:
标签: javascript arrays vue.js object