pdev
pdev

Reputation: 3

lodash collection - add extra custom property in existing objects of collection

This is my first time using lodash and I'm trying to figure out how to update each record within a JSON object. For example, let's say I have a person object:

"person":[
  {
    "firstName" : "Alex",
    "lastName" : "Smith"
  },
  {
    "firstName" : "Madison",
    "lastName" : "Matthews"
  }
]

I would like to add a new field called "fullName" to each record in person that is a combination of their first and last names. Is there a way I can do this using lodash and/or javascript? I don't want to use any other tool.

Thanks!

Upvotes: 0

Views: 1480

Answers (1)

Satyam Koyani
Satyam Koyani

Reputation: 4274

Here if you have persons collection(Array of json objects) then you can add one more property by traversing the collection with lodash function. There are other several ways also.

var persons = [
  {
    "firstName" : "Alex",
    "lastName" : "Smith"
  },
  {
    "firstName" : "Madison",
    "lastName" : "Matthews"
  }
];

var personsWithFullName = _(persons).forEach(function(person) {
      person.fullName = person.firstName + person.lastName;
     return person;
});

or

var newPersonsWithFullName = _.map(persons , function(person) { 
     return _.assign({}, person, {fullName: (person.firstName + person.lastName)});
});

Upvotes: 1

Related Questions