JavaScript:如何使用两个相同的键迭代对象(并获得两个值)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12561482/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
JavaScript: How to iterate object with two the same keys (and get two values)
提问by WHITECOLOR
var obj = { key: value1, key: value2}
I would like to iterate it and get pars of (key and value1) and (key and value2)
我想迭代它并获取 (key and value1) 和 (key and value2) 的解析
if I use simple cycle:
如果我使用简单循环:
for (var i in obj){
console.log(obj[i])
}
I got: key value2 key value2
我得到:key value2 key value2
so obj[i] always take last key
所以 obj[i] 总是取最后一个键
回答by vzwick
Keys in JS objects must be unique.
JS 对象中的键必须是唯一的。
What happens, is:
发生的事情是:
var obj = {
key : value1
}
sets obj['key']
to value1
.
设置obj['key']
为value1
。
The subsequent declaration of key : value2
overwritesyour previous one.
随后的声明将key : value2
覆盖您之前的声明。
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);
回答by saji89
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.
最初 obj.key 设置为value1
,在第二个赋值中value1
被重写为value2
,所以, obj.key 现在是value2
。
所以你不能访问初始值。