你好,我是编程的新手,我偶然发现了按日期对两个数组中的数组数据进行分组的方法。
这是我的数组:
header = [
{"2019-04-22": "Sun, Apr 22, 2019"},
{"2019-04-21": "Sat, Apr 21, 2019"},
]
body = [
{"2019-04-22": "doing customer support”},
{"2019-04-22": "reply to emails"},
{"2019-04-21": "send message to customers"},
]
如何将阵列分为一个阵列,如下例所示
combinearray = {
"2019-04-22": [
"Sun, Apr 22, 2019",
"doing customer support",
"reply to emails",
],
"2019-04-21": [
"Sat, Apr 21, 2019",
"send message to customers",
],
}
按日期对两个数组数据进行分组对我来说似乎并不容易,我是javascript编程的初学者。我将不胜感激。
答案 0 :(得分:4)
您可以按照以下步骤进行操作:
concat()
合并两个数组,即header
和body
reduce()
。并将空对象作为第二个参数(累加器的初始值)传递。reduce()
回调内部,使用Object.keys()[0]
获取日期。[]
。push()
将元素添加到数组中。 注意:这不会删除对header
和body
中的真实对象的引用。
const header = [ {"2019-04-22": "Sun, Apr 22, 2019"}, {"2019-04-21": "Sat, Apr 21, 2019"} ]
const body = [ {"2019-04-22": "doing customer support"}, {"2019-04-22": "reply to emails"}, {"2019-04-21": "send message to customers"}, ]
const res = header.concat(body).reduce((ac,a) => {
let key = Object.keys(a)[0];
ac[key] = ac[key] || [];
ac[key].push(a)
return ac;
},{})
console.log(res)
但是,正如注释中所述,不需要带有键的对象。只需简单的键值数组即可。为此,push()
a[key]
而不是a
。
const header = [ {"2019-04-22": "Sun, Apr 22, 2019"}, {"2019-04-21": "Sat, Apr 21, 2019"} ]
const body = [ {"2019-04-22": "doing customer support"}, {"2019-04-22": "reply to emails"}, {"2019-04-21": "send message to customers"}, ]
const res = header.concat(body).reduce((ac,a) => {
let key = Object.keys(a)[0];
ac[key] = ac[key] || [];
ac[key].push(a[key])
return ac;
},{})
console.log(res)
答案 1 :(得分:4)
您可以使用组合数组,然后使用reduce
let header = [{"2019-04-22": "Sun, Apr 22, 2019"},{"2019-04-21": "Sat, Apr 21, 2019"},]
let body = [{"2019-04-22": "doing customer support"},{"2019-04-22": "reply to emails"},{"2019-04-21": "send message to customers"},]
let final = [...header,...body].reduce((op,inp) => {
let [key,value] = Object.entries(inp)[0]
op[key] = op[key] || []
op[key].push(value)
return op
},{})
console.log(final)