Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

135
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda