如何将键从1数组匹配到另一个对象并获取每个键的总和

时间:2018-08-30 15:20:40

标签: javascript

我有1个具有完整数据的对象,以及2个存在于对象中的键数组,我如何从2个数组中获取每个键的总和。

const data = [{
  DateMeasured: "8/30/2018",
  AsthmaDiaryReading: "100",
  AsthmaDiaryPersonalBest: "100",
  Comment: ""
},{
  DateMeasured: "8/29/2018",
  AsthmaDiaryReading: "200",
  AsthmaDiaryPersonalBest: "150",
  Comment: ""
},{
  DateMeasured: "8/15/2018",
  AsthmaDiaryReading: "300",
  AsthmaDiaryPersonalBest: "50",
  Comment: ""
},{
  DateMeasured: "8/6/2018",
  AsthmaDiaryReading: "100",
  AsthmaDiaryPersonalBest: "200",
  Comment: ""
},{
  DateMeasured: "9/6/2017",
  AsthmaDiaryReading: "500",
  AsthmaDiaryPersonalBest: "100",
  Comment: ""
}
];

总和键,

array = [
      'AsthmaDiaryReading',
      'AsthmaDiaryPersonalBest'
    ]

期望金额应如下:

object = {
  AsthmaDiaryReading: "1200" ,
  AsthmaDiaryPersonalBest: '600'
}

3 个答案:

答案 0 :(得分:4)

您可以使用Array.reduce()

const data = [{
    AsthmaDiaryReading: '100',
    AsthmaDiaryPersonalBest: '100',
  },
  {
    AsthmaDiaryReading: '200',
    AsthmaDiaryPersonalBest: '150',
  },
  {
    AsthmaDiaryReading: '300',
    AsthmaDiaryPersonalBest: '50',
  },
  {
    AsthmaDiaryReading: '100',
    AsthmaDiaryPersonalBest: '200',
  },
  {
    AsthmaDiaryReading: '500',
    AsthmaDiaryPersonalBest: '100',
  },
];

dataKeys = [
  'AsthmaDiaryReading',
  'AsthmaDiaryPersonalBest'
];

const initialArray = dataKeys.reduce((tmp, x) => ({
  ...tmp,

  [x]: 0,
}), {});

const ret = data.reduce((tmp, x) => {
  Object.keys(tmp).forEach((y) => {
    tmp[y] += parseInt(x[y]);
  });

  return tmp;
}, initialArray);

console.log(ret);

答案 1 :(得分:0)

在内部使用reduce循环的for in较短:

const data = [{
    AsthmaDiaryReading: '100',
    AsthmaDiaryPersonalBest: '100',
  },
  {
    AsthmaDiaryReading: '200',
    AsthmaDiaryPersonalBest: '150',
  },
  {
    AsthmaDiaryReading: '300',
    AsthmaDiaryPersonalBest: '50',
  },
  {
    AsthmaDiaryReading: '100',
    AsthmaDiaryPersonalBest: '200',
  },
  {
    AsthmaDiaryReading: '500',
    AsthmaDiaryPersonalBest: '100',
  },
];

var res = data.reduce((acc,c)=>{
    for(let a in c){
        acc[a] = (acc[a] || 0)+parseInt(c[a]);
    }    
    return acc;
},{})//<-- associative array if you change {} for []

console.log(Object.keys(res))

console.log(res)

答案 2 :(得分:0)

一个纯粹的reduce选项,尽管不是很漂亮:

const sumOfKeys = (keys, data) => data.reduce(
  (total, entry) =>
    keys.reduce(
      (acc, k) => ({ ...acc, [k]: (total[k] || 0) + Number(entry[k]) }),
      {},
    ),
  {},
);

sumOfKeys(dataKeys, data)