尝试从映射中获取数组中的正确最终格式,使用 REST API 进行更新,但不能完全 JS



我正在尝试使用Woocommerce REST API格式化一些数据以批量更新。

目标数组格式:

update: [
{
id: 1,
app: 'string1string2string3'
},
{
id: 2,
app: 'string2'
}, 
{
id: 3,
app: 'string2'
},
{
id: 5,
app: 'string2'
}
]

可再生的例子

arr1 = [{
id: 1,
app: 'string1'
}, {
id: 1,
app: 'string2'
}, {
id: 1,
app: 'string3'
}, {
id: 2,
app: 'string2'
}, {
id: 3,
app: 'string2'
}, {
id: 5,
app: 'string2'
}];
let a = new Map();
arr1.forEach((e) => {
if (a.get(e.id)) {
a.get(e.id).app += e.app;
} else {
a.set(e.id, e)
}
})
const finalizado = Array.from(a)
console.log(finalizado);
var temporary, chunk = 100;
for (let i = 0; i < finalizado.length; i += chunk) {
temporary = finalizado.slice(i, i + chunk);
var payloadUp = {
update: temporary
};
console.log(payloadUp);
}

这是一个可重复的例子,我的第一次尝试是只是从地图形成一个数组:

const finalizado = Array.from(a)

这不起作用,然后我试着给它一些格式:

const finalizado = Array.from(a, [key, value] => {
return ([key]: value);
}

但是我想我有点力不从心了,我搞不懂这些格式。

解决方案

使用reduce()Object.values()可以像你想的那样设置一个目标数组:

arr1 = [{
id: 1,
app: 'string1'
}, {
id: 1,
app: 'string2'
}, {
id: 1,
app: 'string3'
}, {
id: 2,
app: 'string2'
}, {
id: 3,
app: 'string2'
}, {
id: 5,
app: 'string2'
}];
const arrayHashmap = arr1.reduce((obj, item) => {
obj[item.id] ? obj[item.id].app = obj[item.id].app.concat(item.app) : (obj[item.id] = { ...item });
return obj;
}, {});
const mergedArray = Object.values(arrayHashmap);
console.log(mergedArray);

最新更新