Skip to content
Advertisement

What is the best way to find index of an item inside an array and that array is inside another away [closed]

I was wondering what is the best way to find the index of an item that is located inside an array, and that array is located inside another array.

This is the kind of data I have:

const list = [
  {
    id: 1,
    items: [
      {
        name: "milk",
        id: 99
      },

      { name: "water", id: 33 }
    ]
  },
  {
    id: 4,
    items: [
      {
        name: "oranges",
        id: 22
      },

      { name: "patatoes", id: 13 }
    ]
  }
];

Lets say that I want to know the index of the item with the name “milk”, I already know the id of the parent object (1), and I also know the id of the item(99).

My goal is to change the name of the item from “milk” to “cheese”, My first idea was to do it like this:

const firstObjectIndex = arr.findIndex(el => el.id === 1) 
if(firstObjectIndex !== -1){
const itemIndex = arr[firstObjectIndex].items.findIndex(item => item.id === 99)

 if(itemIndex !== -1){
  // this is where I change the name to cheese
  arr[firstObjectIndex].items[itemIndex].name = 'Cheese'
 }
}

The method I used above does the job, but I am wondering if there is a better way to do this in JavaScript? Any help would be greatly appreciated

Advertisement

Answer

You don’t really need the index, but the object itself. Therefore, use Array#find. This allows both of the searches to be easily combined into one statement with the optional chaining operator.

const list=[{id:1,items:[{name:"milk",id:99},{name:"water",id:33}]},{id:4,items:[{name:"oranges",id:22},{name:"patatoes",id:13}]}];
let obj = list.find(x => x.id === 1)?.items.find(y => y.name === 'milk');
if(obj) obj.name = 'Cheese';
console.log(list);
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement