0

My object looks like this

{
  "about.php": [
    "#topNav",
    "#botNav",
    "#employees"
  ],
    "index.php": [
    "#blah"
  ]
}

I am looping through it like so

        var validation_messages = obj;

            for (var key in validation_messages) {
               if (validation_messages.hasOwnProperty(key)) {
                   var obj = validation_messages[key];
                    for (var prop in obj) {
                      if(obj.hasOwnProperty(prop)){
                        console.log(prop + " = " + obj[prop]);
                      }
                   }
                }
            }

I am getting this result

0 = #topNav
1 = #botNav
2 = #employees
0 = #blah

I need the name of the object key not the key of the array that is in the objects value. like so:

about.php = #topNav
about.php = #botNav
about.php = #employees
index.php = #blah

I will be pushing new values into the arrays if they do not exists like so:

{
  "about.php": [
    "#topNav",
    "#botNav",
    "#employees"
  ],
    "index.php": [
    "#blah",
    "#newValue"
  ]
}

1 Answer 1

1

You're looping over the second structure incorrectly. It is an array, not an object.

for (var key in validation_messages) {
    if (validation_messages.hasOwnProperty(key)) {
        var obj = validation_messages[key];

        // use a for loop here instead of for...in
        for (var i = 0, l = obj.length; i < l; i++) {
            console.log(key + " = " + obj[i]);
        }
    }
}

DEMO

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.