Prats
Prats

Reputation: 1765

How to add new elements to the object of an array on javascript

I have an var arr = [{name:"Joe"}, {name:"Mark"}]; I have the age array like var ageArr = [{age: 24}, {age: 30}]

I need to programatically add the respective age of the objects

My array need to looks like var arr = [{name:"Joe", age: 24}, {name:"Mark", age: 30}];

I am using javascript and included the library underscore.js.

Is there a cleaner way to achieve this. could some one help with a code snippet for this.

Upvotes: 1

Views: 4102

Answers (3)

coderz
coderz

Reputation: 4999

The most straightforward way:

// make sure names and ages are same length
function mapNameWithAge(names, ages) {
  var len = names.length,
    ans = [];
  for(var i=0;i<len;i++) {
    var obj = {
      "name": names[i].name,
      "age": ages[i].age
    }
    ans.push(obj);
  }
  return JSON.stringify(ans)
}

var arr = [{name:"Joe"}, {name:"Mark"}],
  ageArr = [{age: 24}, {age: 30}];
var result = mapNameWithAge(arr, ageArr);
console.log(result);

Upvotes: 0

Sam4Code
Sam4Code

Reputation: 551

You can use simple Javascript code to achieve this.

var arr = [{name:"Joe"}, {name:"Mark"}];
var ageArr = [{age: 24}, {age: 30}]


var newArr = []


for(var i =0 ; i < arr.length ; i++)
{
   var newObj = new Object();
   newObj.name = arr[i].name;
   newObj.age = ageArr[i].age;
   
   newArr.push(newObj)
}

alert(JSON.stringify(newArr))

Click on Run Code Snippet

Upvotes: 1

zerkms
zerkms

Reputation: 255005

you can

var newArr = arr.map(function(v, i) {
    return _.extend(v, ageArr[i]);
});

If you don't like using a free variable ageArr and access by index - you could zip them first:

var newArr = _.zip(arr, ageArr).map(function(v) {
    return _.extend(v[0], v[1]);
});

JSFiddle: http://jsfiddle.net/wrq2Lo8m/

Upvotes: 3

Related Questions