0

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
  • 10
  • 50
  • 116
  • 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

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,068
  • 2
  • 13
  • 27