我有2个JSON数组和1个日期来表示关键,如何在每个日期的基础上将它排成一行并总结钢和混凝土?
var a = ['Nov 1 2016','Nov 2 2016','Nov 3 2016','Nov 4 2016'];
var b = [{Date:'Nov 1 2016', steel:10.98},{Date:'Nov 3 2016', steel:5.67},{Date:'Nov 4 2016', steel:3.14}]
var c = [{Date:'Nov 1 2016', concrete:9.10},{Date:'Nov 2 2016', concrete:16.8},{Date:'Nov 4 2016', concrete:7.20}]
//output sum of steel and concrete
var x = [{Date:'Nov 1 2016', val:20.08},{Date:'Nov 2 2016', val:16.8},{Date:'Nov 3 2016', val:5.67},{Date:'Nov 4 2016', val:10.34}]
答案 0 :(得分:1)
你可以做的是遍历日期数组,并且对于每个日期,找到b
和c
中的相应项目(如果找不到则提供具有0值的默认项目),并总结他们各自的steel
和concrete
属性。
换句话说,将每个日期字符串转换(map)到包含该日期的对象以及该日期的steel
和concrete
之和:
// dates is the `a` array, steelDays is the `b` array, concreteDays is the `c` array
const result = dates.map(date =>
toDateAndValueObj(
date,
sumSteelAndConcrete(
findByDate(steelDays, date),
findByDate(concreteDays, date)
)
)
);
功能将在哪里
// converts a date and a value into an object containing that date and that value
const toDateAndValueObj = (date, val) => ({ date, val });
// takes two objects (or the objects with default values if passed undefined) and sums up their respective `steel` and `concrete` properties
const sumSteelAndConcrete = (s = { steel: 0 }, c = { concrete: 0 }) => s.steel + c.concrete;
// finds an item in the array who's Date property lexicographically equals the given date string
const findByDate = (arr, date) => arr.find(item => item.Date === date);
请注意,为了简单起见,我在这里使用字符串比较。如果您使用的是实际日期,则可能需要构建Date个对象并使用getTime进行比较:
const findByDate = (arr, date) => arr.find(item => new Date(item.Date).getTime() === new Date(date).getTime());
完整演示:
const dates = ['Nov 1 2016','Nov 2 2016','Nov 3 2016','Nov 4 2016'];
const steelDays = [{Date:'Nov 1 2016', steel:10.98},{Date:'Nov 3 2016', steel:5.67},{Date:'Nov 4 2016', steel:3.14}];
const concreteDays = [{Date:'Nov 1 2016', concrete:9.10},{Date:'Nov 2 2016', concrete:16.8},{Date:'Nov 4 2016', concrete:7.20}];
const toDateAndValueObj = (date, val) => ({ date, val });
const sumSteelAndConcrete = (s = { steel: 0 }, c = { concrete: 0 }) => s.steel + c.concrete;
const findByDate = (arr, date) => arr.find(item => item.Date === date);
const result = dates.map(date =>
toDateAndValueObj(
date,
sumSteelAndConcrete(
findByDate(steelDays, date),
findByDate(concreteDays, date)
)
)
);
console.log(result);

答案 1 :(得分:0)
var b = [{Date:'Nov 1 2016', steel:'10.98'},{Date:'Nov 3 2016', steel:'5.67'},{Date:'Nov 4 2016', steel:'3.14'}];
var c = [{Date:'Nov 1 2016', concrete:'9.10'},{Date:'Nov 2 2016', concrete:'16.8'},{Date:'Nov 4 2016', concrete:'7.20'}];
var obj = {};
for(var index in b){
obj[b[index]['Date']] = b[index]['steel'];
}
for(index in c){
if(obj.hasOwnProperty(c[index]['Date'])){
obj[c[index]['Date']] += c[index]['concrete'];
}else{
obj[c[index]['Date']] = c[index]['concrete'];
}
}
var result = [];
for(var key in obj){
result.push({Date:key, val:obj[key]});
}
console.log(result);