在嵌套数组中查找具有值的对象并添加属性

时间:2019-09-04 00:44:44

标签: javascript arrays lodash

我有一个带有嵌套数组的数据结构,如下所示。我正在尝试找到最简单的方法来使用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"
            }
        ]
    }
]

1 个答案:

答案 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)