2

I have array enter image description here

as you can see, it has 4 elements (created_at, first_name, id, last_name).

My question is, how do I destructure it into an array that has 2 elements(id, name)

(name should be first_name + last_name)

2
  • Kindly post the real javascript data rather than image from console. Commented Jan 13, 2020 at 10:45
  • 1
    What you have is an array of 2 objects, each object containing 4 keys Commented Jan 13, 2020 at 10:46

2 Answers 2

7

Just use map:

arr.map(({id, first_name, last_name}) => { return {id, name: first_name + ' ' + last_name}})

An example:

let arr = [{
    "id": 100,
    "first_name": "first_name_1",
    "last_name": "last_name_1",

},
{
    "id": 101,
    "first_name": "first_name_2",
    "last_name": "last_name_2",
}
];

console.log(arr.map(({id, first_name, last_name}) => { return {id, name: first_name + ' ' + last_name}}))

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

3 Comments

Maybe add a space between first_name and last_name
I wrote the same answer but before I pressed post this answer came in haha, upvoted this
You can also wrap the object in parenthesis so you don't need return keyword
1

You can use map to get the new array as your requirements. Code look likes

const data = [
  {created_at:"2020-01-05", first_name:"Sadio", id:1, last_name:"Marne"},
  {created_at:"2020-01-05", first_name:"Mohamed", id:2, last_name:"Salah"},
  {created_at:"2020-01-05", first_name:"Palash", id:3, last_name:"Kanti"},
  {created_at:"2020-01-05", first_name:"Tuhin", id:4, last_name:"Saha"},
  ]

let newArray=data.map(res=>{
  return {id:res.id, name:res.first_name+' '+res.last_name}
});

console.log(newArray)

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.