node.js中的JSON迭代

时间:2015-07-04 19:58:46

标签: javascript arrays json node.js loops

[
  {
    "Hs": 5,
    "Type": "Support",
    "By": "William Shake the Speare",
    "Product": "SA",
    "Customer": "Huxley",
    "State": "In progress"
  },
  {
    "Hs": 2,
    "Type": "Support",
    "By": "Orwells",
    "Product": "Web",
    "Customer": "Infranet",
    "State": "Closed"
  }]

我有很多这样的对象,需要拿客户和总和(加)他所有的“Hs”值。所以最终的数组就像:

[
{
    "Customer" : "Infranet",
    "Total_hs" : "18" 
},
{
    "Customer" : "Huxley",
    "Total_hs" : "11" 
}
]

我试图找出lodash和节点foreach函数,但不能,你能帮我吗?谢谢!

2 个答案:

答案 0 :(得分:1)

首先,您必须确保将输入数据作为javascript对象(因此,如果它是json字符串,则需要使用类似var items = JSON.parse(input_string)的内容进行解析)

var items = [{
  "Hs": 5,
  "Type": "Support",
  "By": "William Shake the Speare",
  "Product": "SA",
  "Customer": "Huxley",
  "State": "In progress"
}, {
  "Hs": 2,
  "Type": "Support",
  "By": "Orwells",
  "Product": "Web",
  "Customer": "Infranet",
  "State": "Closed"
}]

...接下来,创建汇总的Hs值数组......

var totals = _.reduce(items, function(memo, item) {
  // make sure that the customer is created on the output object, or initialise it to zero
  memo[item.Customer] = memo[item.Customer] || 0;
  // increment the Hs value with the current item's Hs value
  memo[item.Customer] += item.Hs;
  // return the current object for the next iteration of the loop
  return memo;
// pass empty object to initialise reduce
}, {});

总计现在应该有对象数组,客户名称为键,总Hs为值。

...接下来,重新格式化数组以匹配所需的数据格式...

var target_array = _.map(totals, function(item, key) {
  return {
    Customer: key,
    Total_hs: item
  }
});

...检查输出是否正确......

console.log(target_array);

答案 1 :(得分:0)

鉴于JSON是作为JavaScript对象提供的(下面示例中为items):

var items = [{
    "Hs": 5,
    "Type": "Support",
    "By": "William Shake the Speare",
    "Product": "SA",
    "Customer": "Huxley",
    "State": "In progress"
  }, {
    "Hs": 2,
    "Type": "Support",
    "By": "Orwells",
    "Product": "Web",
    "Customer": "Infranet",
    "State": "Closed"
}];
var collected = _.map(_.keys(_.grouped(items, "Customer")), function(k) {
  return {
    Customer: k,
    Hs: _.reduce(grouped[k], function(accumulator, v) {
        return accumulator + v.Hs;
      }, 0)
  };
});