[英]How to loop through array containing objects and array of objects in JS
我有以下數據:
const store = [{
name: "outside",
color: "lightpink",
position: [-400, 0, 300],
url: "src/assets/picture1.jpg",
link: 1,
},
[{
name: "To the Yard",
color: "lightblue",
position: [-100, 0, 900],
url: "src/assets/picture5.jpg",
link: 2,
},
{
name: "To the Room",
color: "lightblue",
position: [-100, 0, 900],
url: "src/assets/picture5.jpg",
link: 0,
},
],
{
name: "Hall",
color: "red",
position: [20, 10, 0],
url: "src/assets/picture3.jpg",
link: 1,
},
// ...
];
而我想要實現的是通過使用 JS 中的 map() 函數將所有鏈接屬性數據放入新數組中。 問題是我在數組中也有對象數組,所以我需要將 2 和 0 與 1, 1 一起放入。所以結果應該是 [1, 2, 0, 1]。 為了實現這一點,我嘗試了這個:
store.map((entry) => {
if (Array.isArray(entry)) {
return entry.map(item => item.url)
} else {
return entry.url
}
})
但沒有結果
您可以將Array#flatMap
與數組的遞歸映射一起使用。
const getLink = o => Array.isArray(o) ? o.flatMap(getLink) : o.link, store = [{ name: "outside", color: "lightpink", position: [-400, 0, 300], url: "src/assets/picture1.jpg", link: 1 }, [{ name: "To the Yard", color: "lightblue", position: [-100, 0, 900], url: "src/assets/picture5.jpg", link: 2 }, { name: "To the Room", color: "lightblue", position: [-100, 0, 900], url: "src/assets/picture5.jpg", link: 0 }], { name: "Hall", color: "red", position: [20, 10, 0], url: "src/assets/picture3.jpg", link: 1 }], result = store.flatMap(getLink); console.log(result);
你可以.flat
( Array.prototype.flat() ) 數組然后.map
const res = store.flat().map((s) => s.link)
const store = [ { name: "outside", color: "lightpink", position: [-400, 0, 300], url: "src/assets/picture1.jpg", link: 1, }, [ { name: "To the Yard", color: "lightblue", position: [-100, 0, 900], url: "src/assets/picture5.jpg", link: 2, }, { name: "To the Room", color: "lightblue", position: [-100, 0, 900], url: "src/assets/picture5.jpg", link: 0, }, ], { name: "Hall", color: "red", position: [20, 10, 0], url: "src/assets/picture3.jpg", link: 1, }, // ... ] const res = store.flat().map((s) => s.link) console.log(res)
您可以展平數組,然后調用map()
函數。
const store = [ { name: "outside", color: "lightpink", position: [-400, 0, 300], url: "src/assets/picture1.jpg", link: 1, }, [ { name: "To the Yard", color: "lightblue", position: [-100, 0, 900], url: "src/assets/picture5.jpg", link: 2, }, { name: "To the Room", color: "lightblue", position: [-100, 0, 900], url: "src/assets/picture5.jpg", link: 0, }, ], { name: "Hall", color: "red", position: [20, 10, 0], url: "src/assets/picture3.jpg", link: 1, }, ]; let result = store.flat().map(e => e.url); console.log(result);
flat
你的陣列,然后映射展平的陣列。
store.flat().map(s => s.url)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.