[英]Trying to get the right final format in an Array from a Map, to update using a REST API, but can't quite 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);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.