On JavaScript, I have the following JSON:
var mJSON = {
"monster":[
{"id":"150","name":"Richard"},
{"id":"100","name":"Gregory"},
{"id":"200","name":"Rachel"},
{"id":"250","name":"Mike"}
]
}
I need to refine this object by a string inputted by the user. For example: “100”.
The result should be a new JSON like this:
var zJSON = {
"monster":[
{"id":"100","name":"Gregory"}
]
}
I tried looking in Google on easy ways to run through a JavaScript object searching for a string, but without success. There’s nothing like jQuery’s $.inArray too, as far I know. Anyone has any idea?
I’m thinking about converting this JSON into a string, grep it for the value inputted by the user, and then converting the string to JSON again, but I think this will be too troublesome for something that could be easy to achieve.
How about using $.map?
JQuery.map() applies function to each argument of the array (
monsters) and produces the new array that contains the values returned by the function. What is important in this case is that if function returnsnullthen the element is removed from the resulting array.EDIT:
As @Jan has kindly suggested in his comment $.grep suits even better! Here is the code example for your monsters: