我有一个带有嵌套数组的数据结构,如下所示。我正在尝试找到最简单的方法来使用id: 3
查找日历,然后向该日历添加属性show: false
。使用香草javascript(首选)或lodash。
accounts: [
{
name: "account1",
calendars: [
{
id: 1,
name: "calendar1account1"
},
{
id: 2,
name: "calendar2account1"
}
]
},
{
name: "account2",
calendars: [
{
id: 3,
name: "calendar1account2"
},
{
id: 4,
name: "calendar2account2"
}
]
}
]
答案 0 :(得分:3)
如果您试图找到最简单的方法,那么几个嵌套的for
循环就不会出错。
const obj = {"accounts":[{"name":"account1","calendars":[{"id":1,"name":"calendar1account1"},{"id":2,"name":"calendar2account1"}]},{"name":"account2","calendars":[{"id":3,"name":"calendar1account2"},{"id":4,"name":"calendar2account2"}]}]}
const hideCalendar = (accounts, calendarId) => {
for (let i = 0; i < accounts.length; i++) {
for (let j = 0; j < accounts[i].calendars.length; j++) {
if (accounts[i].calendars[j].id === calendarId) {
accounts[i].calendars[j].show = false
return // exit early to prevent unnecessary loops
}
}
}
}
hideCalendar(obj.accounts, 3)
console.info(obj.accounts)
或者,您可以使用Array.prototype.flatMap()
将其简化为仅日历,然后使用Array.prototype.find()
查找所需的日历并设置show
属性(如果找到)
const obj = {"accounts":[{"name":"account1","calendars":[{"id":1,"name":"calendar1account1"},{"id":2,"name":"calendar2account1"}]},{"name":"account2","calendars":[{"id":3,"name":"calendar1account2"},{"id":4,"name":"calendar2account2"}]}]}
const hideCalendar = (accounts, calendarId) => {
let found = accounts.flatMap(({ calendars }) => calendars)
.find(({ id }) => id === calendarId)
if (found) {
found.show = false
}
}
hideCalendar(obj.accounts, 3)
console.info(obj)