Javascript将对象存储在数组中

时间:2014-05-13 17:24:42

标签: javascript arrays

function(data) {
    var lob = new LOBslist(); //new object
    var returnLOB = []; //array init
    for (var i1r= 0; i1r < data.length; i1r++) { 
        var cLob = data[i1r];
        lob.name = cLob.name;
        lob.id = cLob.id;

        returnLOB.push(lob); //adding to array?
        console.log(lob); //right here
  }

  console.log(returnLOB);
  return returnLOB;
}

数据的格式类似于

{"name":"RYI","id":2,"name":"BIB","id":1}

我想访问上述数据,将每个名称和id存储在名为lob的对象中,并将每个对象存储在数组returnLOB中。

每次循环浏览console.log(lob)时,我都会得到正确的对象: RYI id:2 BIB id:1 然后

但是当我尝试将它们存储在returnLOB数组中时,它会输出第二个对象而不是每个对象一次。

知道这里有什么问题吗?

2 个答案:

答案 0 :(得分:2)

function(data) {
        var returnLOB = []; //array init
        for (var i1r= 0; i1r < data.length; i1r++) { 
                var lob = new LOBslist(); //new object
                var cLob = data[i1r];
                lob.name = cLob.name;
                lob.id = cLob.id;

                returnLOB.push(lob); //adding to array?
                console.log(lob); //right here

        }

        console.log(returnLOB);
        return returnLOB;

    }

将lob的声明移动到循环中。现在,您正在重复使用相同的对象并将其多次添加到数组中。每次循环都会更新相同的对象。

答案 1 :(得分:0)

每次尝试创建lob对象,否则您只需反复添加相同的对象并每次更改它的值。此外,通过使用&#34; for ... in&#34;可以简化您的代码。循环,如图所示:

function(data) {
    var lob;
    var returnLOB = []; //array init
    for (var cLob in data) { 
            lob = new LOBslist(); //new object
            lob.name = cLob.name;
            lob.id = cLob.id;

            returnLOB.push(lob); //adding to array?
            console.log(lob); //right here
    }

    console.log(returnLOB);
    return returnLOB;
}