Javascript add properties with the same name to an object

时间秒杀一切 提交于 2020-01-25 08:40:08

问题


    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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!