hamed
hamed

Reputation: 8033

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.

Upvotes: 0

Views: 250

Answers (2)

Johnnie Zhang
Johnnie Zhang

Reputation: 183

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.

Upvotes: 2

Dhiraj
Dhiraj

Reputation: 33618

You can use jQuery's .grep().

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

Upvotes: 3

Related Questions