简体   繁体   English

在JSON数组中按属性查找对象

[英]Find object by property in JSON array

I have problem with get string in JSON data. 我在JSON数据中获取字符串时遇到问题。 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: 有时它一起改变位置, John从第三名转到第二名:

[
  {
    "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. 如果我使用data[3].age来获取John的年龄,并更改数据位置,我将获取David的年龄。

Is there any method I can use to find the object with name David and get the age value? 有什么方法可以用来查找name David的对象并获取age值?

You can use array.find() method as, 您可以使用array.find()方法,

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

最好使用array.filter() (更好的浏览器支持)

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM