将数组对象移动到数组中

时间:2016-03-14 14:03:39

标签: javascript arrays

我有一组与此类似的对象,

 [{
        name : Client 1,
        total: 900,
        value: 12000
    }, {
        name : Client 2,
        total: 10,
        value: 800
    }, {
        name : Client 3,
        total: 5,
        value : 0
}]

我想要的是从中获取3个数组,一个名称数组

[Client 1, Client 2, Client 3]

和总数数组

[900, 10, 5]

和一组值,

[12000, 800, 0]

我以为我能够像地图或类似的东西,但我对如何使用它感到非常困惑。任何人都可以帮助我吗?

4 个答案:

答案 0 :(得分:2)

使用Array.prototype.map功能



Printing description of $3:
<_UIStackedImageContainerView: 0x7f9404604630; frame = (0 0; 308 308); layer = <_UIStackedImageContainerLayer: 0x7f94046047d0>>
(lldb) po [0x7f9404604630 _whyIsThisViewNotFocusable]
ISSUE: This view returns NO from -canBecomeFocused.
ISSUE: One or more ancestors have issues that may be preventing this view from being focusable. Details: 

    <StationCollectionViewCell 0x7f940434c6c0>:
        ISSUE: This view returns YES from -canBecomeFocused, which will prevent its subviews from being focusable.

    <StationSectionCollectionViewCell 0x7f940403e8e0>:
        ISSUE: This view returns YES from -canBecomeFocused, which will prevent its subviews from being focusable.
&#13;
&#13;
&#13;

来自@Andy的注释

  

这是ES6,因此如果您的浏览器尚未支持,您可能需要转换器。

答案 1 :(得分:1)

如果您对包含每个数组的对象没问题,则以下Array.prototype.reduce将起作用:

var a = [{
        name : "Client 1",
        total: 900,
        value: 12000
    }, {
        name : "Client 2",
        total: 10,
        value: 800
    }, {
        name : "Client 3",
        total: 5,
        value : 0
}];

var res = a.reduce(function(a,b){
    return {
    name: a.name.concat(b.name),
    total: a.total.concat(b.total),
    value: a.value.concat(b.value)
  }
},{
    name: [],
    total:[],
    value:[]
})

console.log(res) // Object {name: Array[3], total: Array[3], value: Array[3]}

答案 2 :(得分:0)

您可以将具有所需键的对象用作数组。

&#13;
&#13;
var data = [{ name: 'Client 1', total: 900, value: 12000 }, { name: 'Client 2', total: 10, value: 800 }, { name: 'Client 3', total: 5, value: 0 }],
    result = function (array) {
        var r = {};
        array.forEach(function (a) {
            Object.keys(a).forEach(function (k) {
                r[k] = r[k] || [];
                r[k].push(a[k]);
            });
        });
        return r;
    }(data);
	
document.write('<pre>name: ' + JSON.stringify(result.name, 0, 4) + '</pre>');
document.write('<pre>total: ' + JSON.stringify(result.total, 0, 4) + '</pre>');
document.write('<pre>value: ' + JSON.stringify(result.value, 0, 4) + '</pre>');
document.write('<pre>the object: ' + JSON.stringify(result, 0, 4) + '</pre>');
&#13;
&#13;
&#13;

答案 3 :(得分:0)

如果我理解你,你需要从1创建3个数组?你可以这样想:

var names=[];
var totals=[];
var values=[];

for(var i=0; i<objectArray.length; i++){
  names.push(objectArray[i].name);
  totals.push(objectArray[i].total);
  values.push(objectArray[i].value);
}