javascript 按属性获取JSON对象
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7452217/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get JSON object by attribute
提问by penguinrob
Say I have this JSON object:
假设我有这个 JSON 对象:
var images = {"success":"true", "images":[
{"id":"1234","url":"asdf","tags":["cookie","chocolate"]},
{"id":"5678","url":"qwer","tags":["pie","pumpkin"]}
]};
What would be the most efficient way to get the url of the image with an id of 5678? Can use jQuery.
获取 id 为 5678 的图像的 url 的最有效方法是什么?可以使用jQuery。
回答by jfriend00
Because it's an array and you're looking for an embedded property, not just a simple array value, there isn't really a super-efficient way to find it. There's the brute force mechanism of just walking through the array and compare each id to what you're looking for.
因为它是一个数组并且您正在寻找一个嵌入的属性,而不仅仅是一个简单的数组值,所以实际上并没有一种非常有效的方法来找到它。有一种蛮力机制,只需遍历数组并将每个 id 与您要查找的内容进行比较。
If you're going to be looking up these kinds of things in this same data structure multiple times and you want to speed it up, then you can convert the existing data structure into a different data structure that's more efficient for accessing by ID like this:
如果你要在同一个数据结构中多次查找这些类型的东西并且你想加快它的速度,那么你可以将现有的数据结构转换成不同的数据结构,这样通过 ID 访问更有效:
var imagesById = {
"1234": {"url":"asdf","tags":["cookie","chocolate"]},
"5678": {"url":"qwer","tags":["pie","pumpkin"]}
}
Then, finding an object by id is as simple as this:
然后,通过 id 查找对象就像这样简单:
imagesById["1234"]
回答by user123444555621
url = $.grep(images.images, function(item) { return item.id === '5678' })[0].url;
回答by Matt Ball
Unless the IDs are sorted, you can't do better than plain old iteration:
除非对 ID 进行排序,否则您不能比普通的旧迭代做得更好:
var images = {"success":"true", "images":[
{"id":"1234","url":"asdf","tags":["cookie","chocolate"]},
{"id":"5678","url":"qwer","tags":["pie","pumpkin"]}
]};
var inner = images.images,
targetId = '5678',
found = null;
for (var i=0; i<inner.length; i++) {
if (inner[i][id] === targetId) {
found = inner[i];
// do stuff...
break;
}
}
回答by Simeon G
You'd have to loop through the array:
你必须遍历数组:
$.each(images.images,function(i,img) {
if(img.url == "5678") {
//do whatever you want with this url
}
}