JavaScript 数组处理
var arr = ['aaa', 'ccc']var data = {
aaa: [{count: 31, date: '202010'}, {count: 32, date: '202011'}, {count: 33, date: '202012'}, {count: 34, date: '202013'}],
bbb: [{count: 10, date: '202010'}, {count: 12, date: '202011'}, {count: 13, date: '202012'}, {count: 14, date: '202013'}],
ccc: [{count: 21, date: '202010'}, {count: 22, date: '202011'}, {count: 23, date: '202012'}, {count: 24, date: '202013'}],
}
最后要的结果
// arr = [
// {aaa:31, ccc:21, date: 202010},
// {aaa:32, ccc:22, date: 202011},
// {aaa:33, ccc:23, date: 202012},
// {aaa:34, ccc:24, date: 202013}
// ]
回答
代码实现:
测试:
var arr = ['aaa', 'ccc']var data = {
aaa: [{count: 31, date: '202010'}, {count: 32, date: '202011'}, {count: 33, date: '202012'}, {count: 34, date: '202013'}],
bbb: [{count: 10, date: '202010'}, {count: 12, date: '202011'}, {count: 13, date: '202012'}, {count: 14, date: '202013'}],
ccc: [{count: 21, date: '202010'}, {count: 22, date: '202011'}, {count: 23, date: '202012'}, {count: 24, date: '202013'}],
}
console.log(JSON.stringify(getResult(data, arr), null, 2))
输出:
[ {
"date": "202010",
"aaa": 31,
"ccc": 21
},
{
"date": "202011",
"aaa": 32,
"ccc": 22
},
{
"date": "202012",
"aaa": 33,
"ccc": 23
},
{
"date": "202013",
"aaa": 34,
"ccc": 24
}
]
function handler(arr, data) { let map = {};
for (let i = 0; i < arr.length; i++) {
const list = data[arr[i]];
for (let j = 0; j < list.length; j++) {
const item = list[j];
if (map[item.date]) {
map[item.date][arr[i]] = item.count;
} else {
map[item.date] = {
date: item.date,
[arr[i]]: item.count
}
}
}
}
console.log(Object.values(map));
}
以上是 JavaScript 数组处理 的全部内容, 来源链接: utcz.com/a/57213.html