Sarah
Sarah

Reputation: 23

Concatenating elements from a multidimensional array into a new array in Javascript

I have this array of object :

   var Ids = [
 
    {
      "firstname": "name_1",
      "surname": "surname_1"
    },
    {
      "firstname": "name_2",
      "surname": "surname_2"
    },
    {
      "firstname": "name_3",
      "surname": "surname_3"
    }
  ]

My goal is to get the following output :

newId = [ name_1surname_1 ,  name_2surname_2 ,  name_1surname_2 ]

I used the join() method in a simpler array as following and got the expected output but I'm struggling with the first one:

var Ids = [
    [1,2,3,4],
    [5,6,7,8],
    [9,10,11,12]
]
var result = [];
for(var i=0; i < Ids.length; i++){
   for (var k=0 ; k < Ids[i].length; k++)
   result = Ids[i].join('')
   console.log(result)
}


### Output 
1234
5678
9101112

Should I convert : to , ? if so how can I do that please

Upvotes: 1

Views: 35

Answers (1)

Spectric
Spectric

Reputation: 31990

You can use Array.map and concatenate the firstname and surname properties:

var Ids = [
  {
    "firstname": "name_1",
    "surname": "surname_1"
  },
  {
    "firstname": "name_2",
    "surname": "surname_2"
  },
  {
    "firstname": "name_3",
    "surname": "surname_3"
  }
]

const result = Ids.map(e => e.firstname + e.surname)
console.log(result)

Upvotes: 1

Related Questions