如何迭代对象数组并基于键构造新的对象数组

时间:2017-03-06 12:06:09

标签: javascript arrays json object

我有一个看起来像这样的对象数组。

enter image description here

目标:根据旧对象构建一个对象阵列

CONSTRAINTS:

1。它在同一个月内

2。基于类别

的组对象

第3。总结每个类别的金额

这就是我希望我的最终数组看起来像

的样子
[
    {
        category: "001",
        amount: "10",
    },
    {
        category: "002",
        amount: "20",
    },
    {
        category: "004",
        amount: "30.2",
    },
]

这是我到目前为止所得到的

expensesObject.forEach((item) => {
  //group item according to month DONE
  if(Moment(item.exactDate).month() === snapIndex) { //snapIndex represents month index

    //construct new object according to category

    //push object to new array
  }
})

1 个答案:

答案 0 :(得分:0)



foreach(var father in fathers)
{
     Response.Write($"Son1={father.Son1}  ");
     Response.Write($"Son2={father.Son2}  ");
     Response.Write($"Son3={father.Son3}  ");
     Response.Write($"Son4={father.Son4}  ");     
     Response.Write(String.Join("  ", father.Son5.Select(son5 => $"Son5={son5}"));    
     Response.Write("<br />");  
}
&#13;
var obj = {
  expensesObject: [{
    amount: "10",
    category: "001",
    exactDate: ""
  }, {
    amount: "20",
    category: "002",
    exactDate: ""
  }, {
    amount: "12.5",
    category: "004",
    exactDate: ""
  }, {
    amount: "17.70",
    category: "004",
    exactDate: ""
  }]
};

//Filter to get data of the month
//obj.filter(o => moment(o.exactDate).month() === snapIndex);

console.log(obj.expensesObject.reduce(function(rv, x) {
    let v = x.category;
    let el = rv.find((r) => r && r.category === v);
    if (el) {
      el.amount += +x.amount;
    } else {
      rv.push({
        category: v,
        amount: +x.amount
      });
    }
    return rv;
  }, []));
&#13;
&#13;
&#13;