使用JavaScript将对象转换为数组转换

时间:2016-04-01 19:03:31

标签: javascript jquery arrays

在这些中我需要添加养老金名称相同的数组值。如果pensionName值相同,则添加所有金额,并将数组重新更改为myoutput数组。

我的主阵列:

Object, Object, Object, Object, Object, Object, Object]
Object
    amount: 2000
    member: "1"
    name: "Peter Andrews"
    pensionName: "1A"
    rowId: "row_1"
Object
    amount: 2000
    member: "1"
    name: "Peter Andrews"
    pensionName: "1A"
    rowId: "row_2"
Object
    amount: 2000
    member: "1"
    name: "Peter Andrews"
    pensionName: "1A"
    rowId: "row_3"
Object
    amount: 2000
    member: "1"
    name: "Peter Andrews"
    pensionName: "1A"
    rowId: "row_4"
Object
    amount: 2000
    member: "2"
    name: "Peter Andrews"
    pensionName: "2A"
    rowId: "row_5"
Object
    amount: 2000
    member: "2"
    name: "Peter Andrews"
    pensionName: "2A"
    rowId: "row_6"
Object
    amount: 2000
    member: "2"
    name: "Peter Andrews"
    pensionName: "2A"
    rowId: "row_7"

我需要输出为:

[Object, Object]
Object
    amount: 8000
    member: "1"
    name: "Peter Andrews"
    pensionName: "1A"
    rowId: "row_1"

Object
    amount: 6000
    member: "2"
    name: "Peter Andrews"
    pensionName: "2A"
    rowId: "row_2"

所以我做了:

Enter code here
_.forEach(pension,function(item) {
    key = item['pensionName'];
    if (key != "0" && key !=""){
        if (typeof(groups[key]) == "undefined") {
            count++;
            str = "row_"+count;
            groups[key] = {'member' : item['member'],'name' : item['name'],'pensionName' : item['pensionName'],'amount' : item['amount'],'rowId' : str};
        }
        else {
            groups[key]['amount'] = parseFloat(groups[key]['amount']) + parseFloat(item['amount']);
        }
    }
});

结果是:

1A:Object, 2A: Object]
1A: Object
    amount :200
    member :1
    name : "hello"
    name2 : 1A
    id : "row_1"
2A: Object
    amount : 200
    member : 2
    name : "hello"
    name2 : "2A"
    id : "row_2"

但我无法将其推入阵列:

var pensionBalance = getPension();
            pensionBalance.map(function(v){
            arr.push(v);
            });

那么如何将其转换为数组并推送或任何其他方法来添加数组值?

3 个答案:

答案 0 :(得分:1)

也许这对您有用,但我不确定如何处理x_value = x_value > 0 ? -Math.abs(x_value) : Math.abs(x_value); 属性。拿全部还是第一次?

  

基本上,此解决方案适用于rowId thisArg thisthis用作临时对象,引用grouped中唯一人的数组项。

     

在forEach循环中,首先检查此人是否已经在grouped数组中并且在this中。如果没有,则会生成一个新对象,并生成一个新属性,其中已分配实际pensionNamethis并将其推送到grouped

     

现在我们可以使用this的密钥访问pensionName对象并添加amount并将rowId推送到数组中。

     

临时this对象:

{
    "1A": {                       // generated in first loop
        "amount": 8000,
        "member": "1",
        "name": "Peter Andrews",
        "pensionName": "1A",
        "rowId": [
            "row_1",              // added in first
            "row_2",              // ... second
            "row_3",              // third
            "row_4"               // forth
        ]
    },
    "2A": {                       // generated in fifth loop
        "amount": 6000,
        "member": "2",
        "name": "Peter Andrews",
        "pensionName": "2A",
        "rowId": [
            "row_5",              // added in fifth
            "row_6",              // ... sixth
            "row_7"               // seventh
        ]
    }
}



var object = [{ amount: 2000, member: "1", name: "Peter Andrews", pensionName: "1A", rowId: "row_1" }, { amount: 2000, member: "1", name: "Peter Andrews", pensionName: "1A", rowId: "row_2" }, { amount: 2000, member: "3", name: "Peter Andrews", pensionName: "1A", rowId: "row_3" }, { amount: 2000, member: "1", name: "Peter Andrews", pensionName: "1A", rowId: "row_4" }, { amount: 2000, member: "2", name: "Peter Andrews", pensionName: "2A", rowId: "row_5" }, { amount: 2000, member: "2", name: "Peter Andrews", pensionName: "2A", rowId: "row_6" }, { amount: 2000, member: "2", name: "Peter Andrews", pensionName: "2A", rowId: "row_7" }],
    grouped = [];

object.forEach(function (a) {
    if (!this[a.pensionName]) {
        this[a.pensionName] = { amount: 0, member: a.member, name: a.name, pensionName: a.pensionName, rowId: [] };
        grouped.push(this[a.pensionName]);
    }
    this[a.pensionName].amount += a.amount;
    this[a.pensionName].rowId.push(a.rowId);
}, {});

document.write('<pre>' + JSON.stringify(grouped, 0, 4) + '</pre>');
&#13;
&#13;
&#13;

答案 1 :(得分:1)

使用Array.forEachArray.map函数考虑以下方法:

var grouped = {}, grouped_arr;
// pension is your initial array
pension.forEach(function(v){
    var key = v["pensionName"];
    if (grouped[key]) {
        if (v["member"] === grouped[key]["member"] 
            && v["name"] === grouped[key]["name"]) {
            grouped[key]["amount"] += v["amount"];
        }
    } else {
        grouped[key] = v;
    }
});

grouped_arr = Object.keys(grouped).map(function(k, i){
    var obj = grouped[k];
    obj["rowId"] = obj["rowId"].substring(0, obj["rowId"].indexOf("_") + 1) + (i+1);
    return obj;
});

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

输出:

[
    {
        "amount": 8000,
        "member": "1",
        "name": "Peter Andrews",
        "pensionName": "1A",
        "rowId": "row_1"
    },
    {
        "amount": 6000,
        "member": "2",
        "name": "Peter Andrews",
        "pensionName": "2A",
        "rowId": "row_2"
    }
]

答案 2 :(得分:1)

替代解决方案:

var output = [];

pension
  .forEach(function (v, i, arr) {

    var exists = output
      .reduce(function (a, c) {
        return c.pensionName === v.pensionName ? true : a;
      }, false);

    if (exists) return;

    var obj = arr
      .filter(function (p) {
        return p.pensionName === v.pensionName;
      })
      .reduce(function (a, c) {
        a.amount = a.amount + c.amount;
        return a
      });

    output.push(obj);
  });

output.map(function (v, i) {
  v.rowId = 'row_' + (i + 1);

  return v;
});