Find object by property in JSON array

大城市里の小女人 提交于 2021-02-08 11:47:27

问题


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?


回答1:


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);



回答2:


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

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


来源:https://stackoverflow.com/questions/50196745/find-object-by-property-in-json-array

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!