[Vuejs]-Lodash deep filter and map nested object

1👍

You could use nested for...of loops with destructuring. If an item has the provided name, return the item. Apply the same approach to updateItemValue as well

const data=[{panels:[{title:"Panel 1",items:[{name:"item1",value:1},{name:"item2",value:2}]},{title:"Panel 2",items:[{name:"item3",value:3},{name:"item4",value:4}]}]},{panels:[{title:"Panel 3",items:[{name:"item5",value:5},{name:"item6",value:6}]}]}];

function getItem(name) {
  for (const { panels } of data)
    for (const { items } of panels)
      for (const o of items)
        if (o.name === name)
          return o

  return; // if no match is found
}

function updateItemValue(name, value) {
  for (const { panels } of data)
    for (const { items } of panels)
      for (const o of items)
        if (o.name === name) {
          o.value = value
          return;
        }
}

console.log(getItem('item1'))
console.log(getItem('item2'))
console.log(getItem('doesntexist'))

updateItemValue('item3', 33) // update the value
console.log(getItem('item3')) // gets the updated value
👤adiga

Leave a comment