0

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)

0

3 Answers 3

3

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));

Sign up to request clarification or add additional context in comments.

Comments

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));

Comments

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.