-2

I have a question, how to get one object from an object array?

The object array looks like this:

const allData = [{
    key1: "value1",
    key2: "value2",
    service: {
      id: "123",
      name: "name1"
    }
  },
  {
    key1: "value1",
    key2: "value2",
    service: {
      id: "222",
      name: "name2"
    }
  }
]

I want to get the object with service.id is 222.

What should the code look like?

Yong Shun
  • 35,286
  • 4
  • 24
  • 46
user1938143
  • 1,022
  • 2
  • 22
  • 46
  • Does this answer your question? [Get JavaScript object from array of objects by value of property](https://stackoverflow.com/questions/13964155/get-javascript-object-from-array-of-objects-by-value-of-property) – cfprabhu Aug 22 '22 at 08:32
  • 1
    This is a simple problem and can be done through some research/effort. – Bhuneshwer Aug 22 '22 at 09:25

2 Answers2

1

Works with Array.find().

returns the first element in the provided array that satisfies the provided testing function. If no values satisfy the testing function, undefined is returned.

const allData = [{
    key1: "value1",
    key2: "value2",
    service: {
      id: "123",
      name: "name1"
    }
  },
  {
    key1: "value1",
    key2: "value2",
    service: {
      id: "222",
      name: "name2"
    }
  }
]

let obj = allData.find(x => x.service.id == "222");

console.log(obj);
Yong Shun
  • 35,286
  • 4
  • 24
  • 46
-1

You could use the filter Array prototype method especially if you could have more than one object having the "222" value for the service.id property in the array.

The filter() method creates a shallow copy of a portion of a given array, filtered down to just the elements from the given array that pass the test implemented by the provided function.

const result = allData.filter(obj => obj.service.id === "222");

console.log(result);
CCBet
  • 416
  • 1
  • 6
  • 19