JavaScript: how to iterate an object with two identical keys (and get two values)

var obj = { key: value1, key: value2} 

I would like to repeat it and get the parses (key and value1) and (key and value2)

if I use a simple loop:

 for (var i in obj){ console.log(obj[i]) } 

I got: key value2 key value2

therefore obj [i] always accepts the last key

+4
source share
2 answers

Keys in JS objects must be unique.

What happens is:

 var obj = { key : value1 } 

sets obj['key'] to value1 .

The subsequent declaration of key : value2 overwrites your previous one.


Possible solution to your problem:

 var obj = { key : [value1, value2] } for (var i in obj) { if (obj[i] instanceof Array) { for (var k; k < obj[i].length; k++) { console.log(obj[i][k]) } } else { console.log(obj[i]); } } 

Another, perhaps more elegant, solution would be to change the way you store your data as follows:

 var obj = [ { key : 'SomeKey' , value : 'foo' }, { key : 'SomeKey' , value : 'bar' }, { key : 'SomeOtherKey', value : 'baz' } ]; 

This obviously allows you to use multiple records with the same key. The query can be executed somewhere in these lines:

 values = []; for (var i = 0; i < obj.length; i++) { if (obj[i].key === 'SomeKey') { values.push(obj[i].value); } } console.log(values); 
+8
source

It's impossible. As in the declaration:

 var obj = { key: value1, key: value2} 

Initially, obj.key is set to value1 , in the second assignment, value1 overwritten with value2 . So now obj.key value2 .
Thus, you cannot get the initial value.

+2
source

Source: https://habr.com/ru/post/1435870/


All Articles