简体   繁体   中英

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.

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/

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

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM