0

Although, it ran fine on small data. I need help looping through JSON in this form:

var current_value = 2;
json_data = {"2":"first information","3":"Second informaton","4":"Third information"}

What I want to do is get the value in the json_data that corresponds to current_value of 2 The problem is that I keep getting " anytime I run this loop:

for(x in json_data){
    if(x === current_value){
        extracted = json_data[current_value];
    }
}
13
  • 4
    It's not actually Json you have there, it's an object literal. Commented Oct 4, 2017 at 12:38
  • 2
    benalman.com/news/2010/03/theres-no-such-thing-as-a-json Commented Oct 4, 2017 at 12:39
  • @Keith unless it is actually a JSON string and they're not parsing it, may be why they are getting " Commented Oct 4, 2017 at 12:39
  • You loop through all keys, and if the current key equals a predetermined value, you take the predetermined value out of the object… The entire loop is superfluous for doing that. Commented Oct 4, 2017 at 12:40
  • @George — If that is the case, then their code example does not represent their real code. Commented Oct 4, 2017 at 12:40

1 Answer 1

2

JavaScript property names are strings. 2 is a number. === does not do type conversion. "2" !== 2.

You should set current_value to "2" instead of 2.


The loop is pointless though.

A more sensible approach would be:

var extracted;
if (current_value in json_data) { 
    extracted = json_data[current_value];
}

… or even just skip the if statement. extracted will be undefined either way if the property doesn't exist.

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

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.