Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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));
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading