2

This is the code:

var groups = {
    "JSON":{
        "ARRAY":[
            {"id":"fq432v45","name":"Don't use me."},

            {"id":"qb45657s","name":"Use me."}
        ]
    }
}

I want to get the name value where the id is "qb45657s" how could this be accomplished? I figured the obvious loop through all of the array and check if it's equal but is there an easier way?

Edit: I cannot change "Array" to an object because I need to know the length of it for a different function.

9
  • This is not valid JSON... is there an enclosing {} around the whole thing? Commented Feb 11, 2013 at 23:23
  • 2
    JSON is text, a string. Your question is about finding a key in a hash. In Javascript that's an object, but JSON can be parsed into structures in other languages as well. EDIT: and after the edit it's Javascript code, no JSON - JSON is a string. Commented Feb 11, 2013 at 23:25
  • 2
    But it is MY point. You should LEARN something. Confusion about what things are eventually leads to trouble. Commented Feb 11, 2013 at 23:26
  • 3
    Boy do you ever need an attitude change. I wouldn't spend a second helping this guy, though clearly he needs it. Commented Feb 11, 2013 at 23:33
  • 1
    Regardless of the questioners comments, I think this is an interesting question but it seems people are voting on the questioner's attitude instead of the question itself. Commented Feb 11, 2013 at 23:51

2 Answers 2

14

You can simply filter on the given id:

groups["JSON"]["ARRAY"].filter(function(v){ return v["id"] == "qb45657s"; });

This will return [{"id":"qb45657s","name":"Use me."}]

Sign up to request clarification or add additional context in comments.

2 Comments

Why use ["JSON"] instead of accessing via .?
@TheSuburbanGangster There ain't no jQuery there.
0

Assuming you had a valid JSON string like this (note I say valid, because you need an enclosing {} or [] to make it valid):

var json = '{"JSON":{
        "ARRAY":[
            {"id":"fq432v45","name":"Don't use me."},
            {"id":"qb45657s","name":"Use me."}
        ]
    }
}';

You would just parse it into an actual object like this:

var jsonObj = JSON.parse(json); // makes string in actual object you can work with
var jsonArray = jsonObj.JSON.ARRAY; // gets array you are interested in

And then search for it like:

var needle = 'qb45657s';
var needleName;
for (var i = 0; i < jsonArray.length; i++) {
    if (jsonArray[i].id === needle) {
        needleName = jsonArray[i].name;
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.