Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

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

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

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!