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

141
Visualizações
How to filter and transform object into two level object

I'm struggling with this problem. I have this object below.

 const originalData = {
  "price1": 100,
  "amount1": 17.46, 
  "price2": 500,
  "amount2": 29,
  "price3": 700,
  "amount3": 40.74
}

I want a new object inside an array like this below.

const newData =[
  {price:100, amount:17.46},
  {price:500, amount:29},
  {price:700, amount:40.74}      
],

I've tried these methods - filter/map/reduce and googled problom for ages to reach to the result that I wanted. but couldn't get it. please tell me how I can solve this problem.

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

0

Assuming the numbers for the keys are consecutive, you can divide the amount of keys by 2 to get the number of objects and create the array using Array#map or Array.from with the keys of the same number.

const originalData = {
  "price1": 100,
  "amount1": 17.46,
  "price2": 500,
  "amount2": 29,
  "price3": 700,
  "amount3": 40.74
}
let res = [...Array(Object.keys(originalData).length/2)]
            .map((_,i)=>({price: originalData[`price${i+1}`], 
                amount: originalData[`amount${i+1}`]}));
console.log(res);

about 4 years ago · Juan Pablo Isaza Relatório

0

You can simply achieve it by using this logic :

const originalData = {
  "price1": 100,
  "amount1": 17.46, 
  "price2": 500,
  "amount2": 29,
  "price3": 700,
  "amount3": 40.74
};

const arr = [];

Object.keys(originalData).forEach((key, index) => {
  if (originalData[`price${index+1}`]) {
    const obj = {};
    obj.price = originalData[`price${index+1}`]
    obj.amount = originalData[`amount${index+1}`]
    arr.push(obj);
  }
});

console.log(arr);

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