2

I am working on an application that gets an id number -- and then I need to find the object that an element with an id. so if I have the value 6 --- I want to gain access to the correct object in this array so I can then read service_name

[{
"id": 2,
"service_name": "benny"
},{
"id": 5,
"service_name": "ready"
},{
"id": 6,
"service_name": "chitty"
},{
"id": 9,
"service_name": "robby"
}]
The Old County
  • 89
  • 13
  • 59
  • 129
  • Please [search thoroughly](/search?q=%5Bjs%5D+find+object+array+property) before posting. More about searching [here](/help/searching). – T.J. Crowder Oct 23 '20 at 09:21
  • Can you try with `Array.find` – kiranvj Oct 23 '20 at 09:21
  • 1
    Assuming `obj` is the obj (parse the json to obj like `JSON.parse(obj)` before you do this), `obj.find(item => item.id === 6)` should get you the item... But this is standard JS and is easily found here with more examples: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find – Rajshri Mohan K S Oct 23 '20 at 09:23
  • thanks man - did the trick – The Old County Oct 23 '20 at 09:32
  • Just to mention. Even though this question is a duplicate it was the first google result since it used the "element" and not "by id" keyword. So people looking for it will find a solution here! – Martin Müsli Oct 17 '22 at 19:40

1 Answers1

2

Use Array.find()

const arr = [{
"id": 2,
"service_name": "benny"
},{
"id": 5,
"service_name": "ready"
},{
"id": 6,
"service_name": "chitty"
},{
"id": 9,
"service_name": "robby"
}]


const six = arr.find(i => i.id === 6)

console.log(six.service_name)
Jason McFarlane
  • 2,048
  • 3
  • 18
  • 30