0

I have a data structure as below with nested arrays. I'm trying to find the simplest way to find the calendar with id: 3 and then add a property show: false to that calendar. Either using vanilla javascript (preferable) or 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 Answer 1

3

If you're trying to find the simplest method, you can't go wrong with a couple of nested for loops.

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)

Alternatively, you can use Array.prototype.flatMap() to reduce this to just the calendars, then use Array.prototype.find() to find the one you want and set the show property (if found)

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)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.