Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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).

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading