PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Friday, November 4, 2022

[FIXED] How do i create a new array with new properties from an existing array

 November 04, 2022     arrays, ecmascript-6, javascript, lambda, reactjs     No comments   

Issue

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

Solution

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 to newItems, the latter will have just one entry: an array. Instead you just need the returned array to be assigned to newItems -- without push

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



Answered By - trincot
Answer Checked By - Mildred Charles (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing