Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

223
Visualizações
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.

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.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Solution

Use reduce() and Object.values() can set a target array like you want:

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

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda