Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
350 views
in Technique[技术] by (71.8m points)

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

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...