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

237
Visualizações
How to access an Object's values using arr.reduce()

I am trying to achieve the below:

var arr = [
 {name: 'width', value: 10}, 
 {name: 'height', value: 20}, 
]

arr.reduce((ack, item)=>{
  ack.width = item.value
  ack.height = item.value
  return ack
},{})

//Expected output:

{width: 10, height: 20}

//Actual output:

{width: 20, height: 20}

Maybe I don't understand how .reduce() works a 100%?

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

0

You need to take name as key.

const
    array = [{ name: 'width', value: 10 }, { name: 'height', value: 20 }],
    result = array.reduce(
        (object, { name, value }) => ({ ...object, [name]: value }),
        {}
    );

console.log(result);

about 4 years ago · Juan Pablo Isaza Relatório

0

reduce method executes a callback function on each element of the array, so in your issue, on every iteration you have an object that contains name and value property. you can achieve your goal like this:

let arr = [
 {name: 'width', value: 10}, 
 {name: 'height', value: 20}, 
]

let result = arr.reduce((ack, item)=>{
  ack[item.name] = item.value
  return ack
},{})

console.log(result);

about 4 years ago · Juan Pablo Isaza Relatório

0

Maybe I don't understand how .reduce() works a 100%?

Appears so. Read the docs

Every time the reducer function is called - ack is what was returned last time from the reducer (or the initial value if it's the first pass) and item is the current item.

It helps to do this:

arr.reduce((ack, item)=>{
  console.log(ack); // this will help you understand
  ack[item.name] = ack[item.value]
  return ack
},{})
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