简体   繁体   English

使用密钥从json数组中获取json对象

[英]fetch json object from json array with a key

I have a json array that contains some json objects. 我有一个包含一些json对象的json数组。 Suppose I have a course object like this: 假设我有一个像这样的course对象:

{"name": "Math", "unit": "3"}

And my json array is look like this: 我的json数组如下所示:

[{"name": "Math", "unit": "3"}, {"name": "Physics", "unit": "3"}, ...]

Now I need to get an object with it's name. 现在,我需要获取一个具有其名称的对象。 For example I want to get the course with "Math" name. 例如,我想获得带有“ Math”名称的课程。 I know It's possible to loop through each array items and check each item name and return an object that its name is equal to "Math", But my array may be too long and this is not good to loop through long array. 我知道可以遍历每个数组项并检查每个项的名称并返回其名称等于“ Math”的对象,但是我的数组可能太长了,这对于遍历长数组是不好的。 This is possible to access object in the array by index, for example array[0] will be equal to {"name": "Math", "unit": "3"} . 可以通过索引访问数组中的对象,例如array[0]将等于{"name": "Math", "unit": "3"} But I want to access array with key, not index. 但是我想用键而不是索引来访问数组。 Is there any better solution for doing that? 有没有更好的解决方案呢? Any help would be greatly appreciated. 任何帮助将不胜感激。

您可以使用jQuery的.grep()

var newArray = $.grep(obj, function(item){ return item.name == "Math"; });

If you need to do multiply query against this array, I suggest you using the following code to convert the array to a json object: 如果您需要对此数组执行乘法查询,建议您使用以下代码将数组转换为json对象:

var newObj = yourArray.reduce(function(previousValue, currentValue, index, array) {
  return previousValue[currentValue.name] = currentValue;
}, {});

You will get: 你会得到:

{"Math":{"name": "Math", unit: "3"}, "Physics":{"name": "Physics", unit: "3"}, ...}

You only loop once but you can reuse it later. 您只循环一次,但以后可以重用。

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

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