【问题标题】:Assign regular javascript array to array of objects将常规 javascript 数组分配给对象数组
【发布时间】:2012-08-06 07:24:39
【问题描述】:

我在 javascript 中有 3 个常规数组

第一个数组:ids[](包含 id 列表)
第二个数组:国家 [] (包含国家名称列表)
第三个数组:code[](包含 国家代码列表)

我需要从这三个数组中创建一个对象数组,比如“comb”,键为“id”、“name”和“code”,以及 3 个数组中的相应值。

例如: 这就是我想要的常规数组

var comb = [
{id:1, name:'United States',code:'US'},
{id:2, name:'China',code:'CH'}
];

谁能告诉我如何做到这一点

【问题讨论】:

  • 仅供参考,您得到的结果是一个对象数组。

标签: javascript


【解决方案1】:
var comb = [];
for (var i=0,n=ids.length;i<n;i++) {
  comb.push({id:ids[i],name:country[i],code:codes[i]});
}

【讨论】:

    【解决方案2】:

    我更喜欢用这种方式定义对象,我认为它看起来更易读。

    function Country(id, country, code) {
        this.id = id;
        this.country = country;
        this.code = code;
    }
    
    var comb = new Array();
    
    for(var i = 0; i < ids.length; i++) {
        var ctry = new Country(ids[i], country[i], codes[i]);
        comb.push(ctry);
    }
    

    【讨论】:

      猜你喜欢
      • 2013-12-31
      • 2012-07-17
      • 1970-01-01
      • 1970-01-01
      • 2010-11-22
      • 2017-12-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多