Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

125
Views
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 answers
Answer question

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 Report

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!