我在陣列中有一個嵌套物件。
{
"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"
}
]
}
uj5u.com熱心網友回復:
你如何for (const [k, item] of comp.items.entries()) {...}用這個替換你的內部回圈(部分):
comp.items = comp.items.map(item => ({ itemData: item.itemDate }));
這只會comp.items用一個新陣列替換每個陣列,其中每個物件只有您想要保留的單個鍵。
如果您實際上不想就地修改資料(即,創建一個具有所需結構的新資料結構,而不是原始資料結構),您可以使用如下所示的內容:
const filtered = {
...this.testingAnimation,
page: this.testingAnimation.page.map(page =>
'comp' in page
? {
...page,
comp: page.comp.map(comp =>
'items' in comp
? {
...comp,
items: comp.items.map(item => ({ itemData: item.itemData }))
}
: comp
)
}
: page
)
}
注意:此解決方案未使用Object.entries(),但如果您想使用它,則應使用符合標準的,Object.entries(someObject)因為通常someObject.entries()未定義。此外,對于陣列,可以使用此函式,但通常使用someArray.forEach(...)or更有意義newArray = someArray.map(item => ...)。MDN是獲得更多幫助的絕佳資源。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/361588.html
標籤:javascript 数组 Vue.js 目的
