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)
CodePudding user response:
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));
CodePudding user response:
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));
CodePudding user response:
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)