When i type this in my console:
当我在我的控制台中键入它时:
var a = {"baz":null, "baz":null, "baz":null, "taz":null};
for (var x in a) {
console.log(x);
}
I only get: "baz" "taz"
我只得到:“baz”“taz”
I need to capture all instances of the key "baz"... is there any way to do this? for...in will only do the above.
我需要捕获关键“baz”的所有实例...有什么办法可以做到这一点吗?因为......只会做上面的事情。
3 个解决方案
#1
I need to capture all instances of the key "baz"... is there any way to do this?
我需要捕获关键“baz”的所有实例...有什么办法可以做到这一点吗?
No there is not. The resulting object won't contain information about duplicate keys in any way.
不,那里没有。生成的对象不会以任何方式包含有关重复键的信息。
Depending on your use case, you can either use an array instead of an object, or use an array as value of the property (and process it accordingly):
根据您的使用情况,您可以使用数组而不是对象,或使用数组作为属性的值(并相应地处理它):
var a = {"baz": [null, null, null], "taz":null};
#2
You can do it by having an array as the value for your key:
您可以通过将数组作为键的值来实现:
{baz: ["homer","bart","liza"], foo:[1,2,3] }
Then to display:
然后显示:
for (var x in a) {
for (var i=0; i < a.length; i++){
console.log(a[i]);
}
}
#3
As Felix pointed out, you cannot have duplicate keys. An alternate way to structure your data may be an Array of dicts.
正如菲利克斯指出的那样,你不能拥有重复的密钥。构建数据的另一种方法可能是一系列dicts。
(I assume that you were trying to store data with each key, 'null' in your question. I represent that with the "other_value" key)
(我假设您在尝试使用每个键存储数据,在您的问题中为'null'。我使用“other_value”键表示该数据)
var a = [{name : "baz", other_value : null}, {name : "baz", other_value : null}, {name : "taz", other_value : null}];
for(var i=0; i<a.length; i++){
console.log(a[i].name);
}
#1
I need to capture all instances of the key "baz"... is there any way to do this?
我需要捕获关键“baz”的所有实例...有什么办法可以做到这一点吗?
No there is not. The resulting object won't contain information about duplicate keys in any way.
不,那里没有。生成的对象不会以任何方式包含有关重复键的信息。
Depending on your use case, you can either use an array instead of an object, or use an array as value of the property (and process it accordingly):
根据您的使用情况,您可以使用数组而不是对象,或使用数组作为属性的值(并相应地处理它):
var a = {"baz": [null, null, null], "taz":null};
#2
You can do it by having an array as the value for your key:
您可以通过将数组作为键的值来实现:
{baz: ["homer","bart","liza"], foo:[1,2,3] }
Then to display:
然后显示:
for (var x in a) {
for (var i=0; i < a.length; i++){
console.log(a[i]);
}
}
#3
As Felix pointed out, you cannot have duplicate keys. An alternate way to structure your data may be an Array of dicts.
正如菲利克斯指出的那样,你不能拥有重复的密钥。构建数据的另一种方法可能是一系列dicts。
(I assume that you were trying to store data with each key, 'null' in your question. I represent that with the "other_value" key)
(我假设您在尝试使用每个键存储数据,在您的问题中为'null'。我使用“other_value”键表示该数据)
var a = [{name : "baz", other_value : null}, {name : "baz", other_value : null}, {name : "taz", other_value : null}];
for(var i=0; i<a.length; i++){
console.log(a[i].name);
}