我在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
值吗?
答案 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) {
}
}
}