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

时间:2018-05-06 06:09:42

标签: javascript json

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

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

有时它会改变位置,John从第3位转到第2位:

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

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

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

2 个答案:

答案 0 :(得分:1)

您可以使用 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);




答案 1 :(得分:0)

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

class Program
{
    private static BackgroundWorker worker = new System.ComponentModel.BackgroundWorker();
    private static AutoResetEvent resetEvent = new AutoResetEvent(false);
    private string[] files;
    static void Main(string[] args)
    {
        worker.DoWork += worker_DoWork;
        worker.RunWorkerCompleted += worker_RunWorkerCompleted;
        worker.ProgressChanged += worker_ProgressChanged;
        worker.WorkerReportsProgress = true;

        Console.WriteLine("Starting Application...");

        worker.RunWorkerAsync();
        resetEvent.WaitOne();

        Console.ReadKey();
    }

    static void worker_ProgressChanged(object sender, ProgressChangedEventArgs e)
    {
        Console.WriteLine(e.ProgressPercentage.ToString());
    }

    static void worker_DoWork(object sender, DoWorkEventArgs e)
    {
        files = GetFiles(@"C:\filesystem"); ///100 files here

        resetEvent.Set();
    }

    static void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
    {
        foreach(string filename in files) {

        }
    }

}