简体   繁体   中英

fetch json object from json array with a key

I have a json array that contains some json objects. Suppose I have a course object like this:

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

And my json array is look like this:

[{"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. 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. This is possible to access object in the array by index, for example array[0] will be equal to {"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:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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