Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

297
Visualizações
How to concatenate multiple properties of same element from an array?

I have an array with personal information like names and ages. I want to combine some of those properties to create a new property for each element in the array.

From this array:

var list = [{name: "James", lastName: "M.", age: 58}, {name: "Rachel", lastName: "W.", age: 51}];

I have created a new entry with:

list.forEach(function(itm){
  itm.username = {...list.firstName, ...list.last};
});

I want to combine list.firstName with list.lastName to create list.username. list.username would consist of a concatenation of list.firstName and list.lastName.

I have tried using the .assign() operator with no success, it just results in TypeError: Cannot read property '0' of undefined. I am for some reason getting the same error message when attempting to simply view individual array properties via console.log(list.firstName[0]);.

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

I am assuming this is javascript (based on the question's tag). In which case the code you are trying to execute seems wrong.

Solution to Question

var list = [{firstName: "James", lastName: "M.", age: 58}, {firstName: "Rachel", lastName: "W.", age: 51}];

list.forEach((entry) => {
   entry.fullName = entry.firstName + " " + entry.lastName; 
});

console.log(list[0].fullName);

In this solution, I am simply looping through all the elements of the array and assigning a new property "fullName" with the values of the element's own property.

There are multiple ways to do it, this is just the most simplest way to clear your understanding.

To display the individual property

console.log(list[0].firstName);

Note, the array index accessor is after the array name list and not after the attribute/property name firstName in this case.

Also in your provided code there is no attribute firstName so do have some checks in place else it will use undefined value and might throw some error depending on your development environment.

Computed Attribute (getter accessor)

You should also think about how the array data will behave if the value of the attributes/properties changes.

For example if you change the firstName attribute/property then you need to remember to update the fullName attribute/property as well, else they will be out of sync.

The more efficient way to do this task is to have the attribute/property as a computed attribute/property (think functions or more accurately getters)

Sample Code

var list = [{
  firstName: "James",
  lastName: "M.",
  age: 58,
  get fullName() {
    return this.firstName + " " + this.lastName;
  },
}, {
  firstName: "Rachel",
  lastName: "W.",
  age: 51,
  get fullName() {
    return this.firstName + " " + this.lastName;
  },
}];


console.log(list[0].fullName);

You can learn more about getters as well as setters at JavaScript Accessors (Getters and Setters)

about 4 years ago · Juan Pablo Isaza Relatório

0

I see two bugs in your code.

  1. The key for first name is 'name' in your list of objects and you've been trying the use 'firstName' while concatenating.

  2. You have been trying to merge the properties of objects in the for loop, where you need to merge the values.

Here's the Solution:

var list = [{firstName: "James", lastName: "M.", age: 58}, {firstName: "Rachel", lastName: "W.", age: 51}];

list.forEach(function(itm){
    itm.username = itm.firstName + " " + itm.lastName; });

console.log(list)

Since the objects are in the list, you will need to provide an index to access the object and its values.

Examples:

console.log(list[0].username)

Or to get the list of usernames only, you can use:

userNames = list.map(function(obj) {
    return obj.username;
});

console.log(userNames)
about 4 years ago · Juan Pablo Isaza Relatório

0

Well, there's no property called list.firstName, I think you mean list.name.

The solution is to create a new object called list.username and combine list.name and list.lastName and since you are inside forEach function, list will be called itm. So, it will be itm.name and itm.lastName.

I have also added + " " + to create a space between the first name and the second name.

var list = [{name: "James", lastName: "M.", age: 58}, {name: "Rachel", lastName: "W.", age: 51}];

list.forEach(function(itm) {
    list.username = itm.name + " " + itm.lastName;

    console.log(list.username);

    /**
    James M.
    Rachel W.
    **/
});

As well as there's no property called list.firstName, you can't access list.firstName, try accessing another one as well.

var list = [{name: "James", lastName: "M.", age: 58}, {name: "Rachel", lastName: "W.", age: 51}];
    
console.log(list[0].name); // James

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda