0

I have just started with react.js and I got a little bit confused with object, accessing, getting values and all that.

I have an object that goes like this:

Array(5) [ 
0: Object {id:"1",name:"Jack"}
1: Object {id:"2",name:"John"}
2: Object {id:"3",name:"Ben"}
]

Now what I want to is access the second name("John" with it's ID). I already have its ID taken from an text input but I am not sure how can I get the object values in a loop and then compare the names with X name for example. Can you please help me figure this out?

wmw147
  • 51
  • 5

2 Answers2

0

try below code:

const result = yourArray.find(item => item.id === YOUR_INPUT_VALUE)
N.SH
  • 616
  • 7
  • 20
0
const myArray = [
{id:"1",name:"Jack"},
{id:"2",name:"John"},
{id:"3",name:"Ben"},]

then

console.log(myArray[1].id)

result

console.log(myArray[1].name)

result

Jack
Adel Benyahia
  • 233
  • 3
  • 10
  • Well, this works but it's supposed to be dynamically. I can't always know at what index is "jack" placed. It can be other than [1]. I have to make it search inside of the array. – wmw147 Oct 17 '22 at 09:55
  • const myObject = [ { id: 1, name: "Jack" }, { id: 2, name: "John" }, { id: 3, name: "Ben" } ]; const findByID = (id) => { const result = myObject.find((item) => item.id === id); console.log(result.name); }; console.log(findByID(2)); – Adel Benyahia Oct 17 '22 at 10:14