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

126
Visualizações
Javascript change single object key name and return arrays

I have an object, I want to change single object key name and return rest of the value as an array.

This is what I am getting

const order = {
      id: "929283652nsjs-sis82ms",
      items: [{ itemCount: 1, itemName: "veg" }],
      createAt: new Date(),
      modifiedAt: new Date()
    }


const newArray = Object.keys(order).flatMap((o) => ({ orderId: o.id }))

console.log(newArray)



//excpected output

const expected = [
 {
      orderId: "929283652nsjs-sis82ms",
      items: [{ itemCount: 1, itemName: "veg" }],
      createAt: new Date(),
      modifiedAt: new Date()
    }
]

console.log(expected)

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

0

Try https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment

const order = {
      id: "929283652nsjs-sis82ms",
      items: [{ itemCount: 1, itemName: "veg" }],
      createAt: new Date(),
      modifiedAt: new Date()
    }


const convert = ({id, ...rest}) => [{orderId: id, ...rest}];

console.log(convert(order));

about 4 years ago · Juan Pablo Isaza Relatório

0

Take the object, destructure the property you want to change from the rest of the properties (I've relabeled it this example), and send back a new object in an array.

const order={id:"929283652nsjs-sis82ms",items:[{itemCount:1,itemName:"veg"}],createAt:new Date,modifiedAt:new Date};

function change(order) {

  // Destructure the id, relabel it
  const { id: orderId, ...rest } = order;
  
  // And then return that new id along
  // with the rest of the object properties in an array
  return [{ orderId, ...rest }];

}

console.log(change(order));

about 4 years ago · Juan Pablo Isaza Relatório

0

What about creating a new key assigning it a value and then deleting the old key.

 const order = {
    id: "929283652nsjs-sis82ms",
    items: [{ itemCount: 1, itemName: "veg" }],
    createAt: new Date(),
    modifiedAt: new Date()
}
order['orderId']=order['id']  // making a new key assigning a value
delete order['id']           // deleteing the old key
console.log(order)
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