在JSON数组中按属性查找对象 [英] Find object by property in JSON array

查看:71
本文介绍了在JSON数组中按属性查找对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在JSON数据中获取字符串时遇到问题.格式如下:

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

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

有时它会一起改变位置,John从第三名转到第二名:

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"
  }
]

如果我使用data[3].age获取John的年龄,并更改数据位置,我将获取David的年龄.

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

我可以使用任何方法用name David查找对象并获取age值吗?

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

推荐答案

您可以使用

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

这篇关于在JSON数组中按属性查找对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆