0

I'm iterating through this object:

var object = { 
   first : {
      child1 : 'test1',
      child2 : 'test2'
   },

    second : {
       child1 : 'test3',
       child2 : 'test4'
    },

   first : {
      child1 : 'test5',
      child2 : 'test6!'
   }
};

with this:

for(var attribute in object){
    alert(attribute + " : " + object[attribute]);
}

First it seemed that it works, but it iterates only on child objects with unique name, so the first object with: first is skipped.

So what's the proper solution to iterate through an entire object?

2 Answers 2

4

JavaScript objects are associative maps, and cannot have multiple values with the same key (name). Your data cannot have that structure.

Another option might be an array of key-value pairs.

var object = [
   ["first", {
      child1 : 'test1',
      child2 : 'test2'
   }],
   ["second", {
       child1 : 'test3',
       child2 : 'test4'
   }],
   ["first", {
      child1 : 'test5',
      child2 : 'test6!'
   }]
];

var i, attribute, value;
for (i = 0; i < object.length; i++) {
    attribute = object[i][0];
    value = object[i][1];
    alert("" + attribute + " = " + value);
}
Sign up to request clarification or add additional context in comments.

Comments

1

There's no problem with the iteration, there's rather a problem with the object. The second property named first replaces the first first, erasing it.

Who's on first?

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.