I am trying to create a new list from an existing list messages
. for a partically reason the reason i am doing this is to be able to pass this new list into a react component, and that react component is expecting an object that has the value of id
and name
, and not what the properties of the existing list are (messageId, and messageName)
I have tried the below amount however the below does not work and i get expected Expression statement is not an assignment or call.
const newItems = []
newItems.push(messages.map(message => {
id: message.messageId;
name: message.messageName
}))
CodePudding user response:
There are these issues:
When using the arrow function syntax, the opening brace of (what you intend to be) the object literal is interpreted as the start of a statement block. To avoid this, wrap the literal in parentheses.
In an object literal the properties should not be separated by semicolon, but by colon
.map
returns the array, so if you push that array tonewItems
, the latter will have just one entry: an array. Instead you just need the returned array to be assigned tonewItems
-- withoutpush
So:
const messages = [{messageId: 1, messageName: "Hello"},{messageId: 2, messageName: "World"}];
const newItems = messages.map(message => ({
id: message.messageId,
name: message.messageName
}));
console.log(newItems);