[英]Create a new array based on array object data
我在數組中有一個嵌套對象。
{
"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"
}
]
}
你如何用這個替換你的內部循環( 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(...)
或newArray = someArray.map(item => ...)
更有意義。 MDN是獲得更多幫助的絕佳資源。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.