I'm using the code below to add element to the array conditionally: when for a domain in arr1 there isn't a kwd in arr2 for that domain then add the keys: domain, key, position: "n/a", date, engine and device.
var arr1 = ["xxx", "yyy"];
var arr2 = [
{ domain: "xxx", kwd: "a", position: 1, date: "2021-05-07T08:05:16.806Z", engine: "google", device: "desktop"},
{ domain: "yyy", kwd: "a", position: 2, date: "2021-05-07T08:05:16.806Z", engine: "google", device: "desktop"},
{ domain: "xxx", kwd: "b", position: 1, date: "2021-05-07T08:05:16.806Z", engine: "google", device: "desktop"},
{ domain: "yyy", kwd: "b", position: 2, date: "2021-05-07T08:05:16.806Z", engine: "google", device: "desktop"},
{ domain: "yyy", kwd: "c", position: 2, date: "2021-05-07T08:05:16.806Z", engine: "google", device: "desktop"},
{ domain: "xxx", kwd: "d", position: 1, date: "2021-05-07T08:05:16.806Z", engine: "google", device: "desktop"}
];
const grouped = arr2.reduce((group, entry) => {
const lookup = group[entry.kwd] || {};
return {
...group,
[entry.kwd]: {
...lookup,
[entry.domain]: entry
}
};
}, {});
const filledIn = Object.entries(grouped).reduce(
(arr, [key, group]) => [
...arr,
...arr1.map((domain) =>
domain in group
? group[domain]
: {
domain,
kwd: key,
position: "n/a",
date: grouped.date,
engine: grouped.engine,
device:grouped.device,
}
)
],
[]
);
console.log(filledIn);
The script works fine but return undefined date, engine and device.
...
{
date: undefined,
device: undefined,
domain: "yyy",
engine: undefined,
kwd: "d",
position: "n/a"
}]
How can I fix this?
Thanks
undefined?