简体   繁体   English

试图从地图中获得正确的最终格式,以使用 REST API 进行更新,但不能完全 JS

[英]Trying to get the right final format in an Array from a Map, to update using a REST API, but can't quite JS

I'm trying to format some data to batch update using Woocommerce REST API.我正在尝试使用 Woocommerce REST API 格式化一些数据以进行批量更新。

Target array format:目标数组格式:

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

Reproducible example可重现的例子

 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); }

This is a reproducible example, my first try was to just form an Array from the Map:这是一个可重现的示例,我的第一次尝试是从地图中形成一个数组:

const finalizado = Array.from(a)

That didn't work, then I tried to give it some format:那没有用,然后我尝试给它一些格式:

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

But I'm out of my depth I think, I can't get my head around the formatting.但是我认为我已经超出了我的深度,我无法理解格式。

Solution解决方案

Use reduce() and Object.values() can set a target array like you want:使用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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM