Reputation: 183
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)
Upvotes: 2
Views: 1709
Reputation: 616
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)
Upvotes: 1
Reputation: 38094
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}}))
Upvotes: 7