Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript: How to iterate object with two the same keys (and get two values)

Tags:

javascript

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

I would like to iterate it and get pars of (key and value1) and (key and value2)

if I use simple cycle:

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

I got: key value2 key value2

so obj[i] always take last key

like image 678
WHITECOLOR Avatar asked Sep 24 '12 08:09

WHITECOLOR


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, possibly more elegant, solution would be to modify the way you store your data like so:

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

This obviously allows for multiple entries with the same key. The querying could be done somewhere along these lines:

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

console.log(values);
like image 169
vzwick Avatar answered Sep 27 '22 22:09

vzwick


This is not possible. As in the declaration:

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

Initially obj.key is set as value1, in the second assignment value1 is rewritten with value2, So, obj.key is now value2.
So you cannot access the initial value.

like image 22
saji89 Avatar answered Sep 27 '22 21:09

saji89