-1

I know how to operate on array of objects but never had the necessity to populate an array data into another. I need to populate firstname + lastname field into name field of birth array

let birth = [
    {name: '' }
]

firstly my array is empty and i want to poplulate it with these datas

let names = [
   {firstname: "Julien", lastname: "DEHAIS"},
   {firstname: "Cyril", lastname: "GUIGUIAN"},
   {firstname: "Pascal", lastname: "BOUTRIN"},
   {firstname: "Franck", lastname: "BORDERIE"},
   {firstname: "Arnold", lastname: "GIRARD"}
]

to get something like this

let birth = [
    {name: 'Julien DEHAIS' },
    {name: 'Cyril GUIGUIAN' },
    {name: 'Pascal BOUTRIN' },
    {name: 'Franck BORDERIE' },
    {name: 'Arnold GIRARD' }
]

Kindly someone help me in this please

Jack Bashford
  • 43,180
  • 11
  • 50
  • 79
Ovy MC
  • 89
  • 6

2 Answers2

1

You can use map() and return a new object with name property

let names = [ {firstname: "Julien", lastname: "DEHAIS"}, {firstname: "Cyril", lastname: "GUIGUIAN"}, {firstname: "Pascal", lastname: "BOUTRIN"}, {firstname: "Franck", lastname: "BORDERIE"}, {firstname: "Arnold", lastname: "GIRARD"} ]

const res = names.map(x => ({name: `${x.firstname} ${x.lastname}`}))
console.log(res)
Maheer Ali
  • 35,834
  • 5
  • 42
  • 73
  • JavaScript objects are *unordered* - the second one is very unreliable (what if the values get swapped? `DEHAIS Julien`) – Jack Bashford May 28 '19 at 09:00
1

Simple map:

let names = [{firstname:"Julien",lastname:"DEHAIS"},{firstname:"Cyril",lastname:"GUIGUIAN"},{firstname:"Pascal",lastname:"BOUTRIN"},{firstname:"Franck",lastname:"BORDERIE"},{firstname:"Arnold",lastname:"GIRARD"}];
const res = names.map(({ firstname, lastname }) => ({ name: firstname + " " + lastname }));
console.log(res);
.as-console-wrapper { max-height: 100% !important; top: auto; }

ES5 syntax:

var names = [{firstname:"Julien",lastname:"DEHAIS"},{firstname:"Cyril",lastname:"GUIGUIAN"},{firstname:"Pascal",lastname:"BOUTRIN"},{firstname:"Franck",lastname:"BORDERIE"},{firstname:"Arnold",lastname:"GIRARD"}];
var res = names.map(function(e) {
  return { name: e.firstname + " " + e.lastname };
});
console.log(res);
.as-console-wrapper { max-height: 100% !important; top: auto; }
Jack Bashford
  • 43,180
  • 11
  • 50
  • 79