[英]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)我想迭代它并获取 (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] 总是取最后一个键
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
overwrites your 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);
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
.最初 obj.key 设置为value1
,在第二次赋值中value1
被改写为value2
,因此, obj.key 现在是value2
。
So you cannot access the initial value.所以你不能访问初始值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.