4

I have problem with get string in JSON data. Format as below:

[
  { "name": "Alice", "age": "20" },
  { "id": "David", "last": "25" },
  { "id": "John", "last": "30" }
]

Sometime it changes position together, John from 3rd place go to 2nd place:

[
  { "name": "Alice", "age": "20" },
  { "name": "John", "age": "30" },
  { "name": "David", "age": "25"}
]

If i use data[3].age to get John's age, and data change position, I will get David's age.

Is there any method I can use to find the object with name David and get the age value?

2
  • 9
    Possible duplicate of Find object by id in an array of JavaScript objects Commented May 6, 2018 at 6:12
  • data[3].age will give you an index error. Commented May 6, 2018 at 8:41

2 Answers 2

9

You can use array.find() method as,

var myArray = [
  {
    "name": "Alice",
    "age": "20"
  },
  {
    "name": "John",
    "age": "30"
  },
  {
    "name": "David",
    "age": "25"
  }
];

//Here you are passing the parameter name and getting the age 
//Find will get you the first matching object
var result = myArray.find(t=>t.name ==='John').age;
console.log(result);

Sign up to request clarification or add additional context in comments.

1 Comment

Work like charm. Thank you very much.
5

It's better to use array.filter() (better browser support)

myArray.filter(function(el){return el.name == "John"})[0].age

1 Comment

Although Array.filter has better browser support than Array.find, I'd like to point out that find will return when it finds a match, whereas filter will go through every item in the array. So, it will perform worse if the array is large. In those cases, regular for loop with break statements should be preferred.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.