对象的键/值对数组

时间:2015-12-23 12:57:50

标签: javascript

我想改变这个

var data = [60, rose, 40, rose1, 20, rose2];

到这个

var data: [{
  value: 60,
  name: 'rose'
}, {
  value: 40,
  name: 'rose1'
}, {
  value: 20,
  name: 'rose2'
}];

2 个答案:

答案 0 :(得分:5)

你可以这样做:

var data = [60, "rose", 40, "rose1", 20, "rose2"]

var dataObj = []
for (var i = 0; i < data.length; i+=2) {
  dataObj.push({
    value: data[i],
    name: data[i + 1]
  })
}

// Demo Output
document.write(JSON.stringify(dataObj))

答案 1 :(得分:1)

仅仅为了完整性,即使对于不均匀的物品也是如此:

var data = [60, "rose", 40, "rose1", 20, "rose2", 30],
    object = data.reduce(function (r, a, i, d) {
        if (i % 2) {
            r[d[i - 1]] = a;
        }
        return r;
    }, {});

document.write('<pre>' + JSON.stringify(object, 0, 4) + '</pre>');