问题
var elements = document.getElementsByClassName("someClass");
var obj = {};
for (var i = 0; i < elements.length; i++){
obj.userId = elements[i].id
}
// output: obj = {userId: 1, userId: 2, userId: 3.....etc}
Is it possible in some way? Thanks.
回答1:
keys in Object
must be unique, you can try use Array
, like this
var obj = [];
var data = {};
for (var i = 0; i < elements.length; i++) {
data = {
userId: elements[i].id
};
obj.push(data);
}
// [ {userId: 1}, {userId: 2} ... ]
回答2:
The JSON RFC says "the names within an object SHOULD be unique" - see here for more info however should your object have a duplicate key the last occurrence will be used.
An array would be a better solution for your data.
来源:https://stackoverflow.com/questions/34175975/javascript-add-properties-with-the-same-name-to-an-object