简体   繁体   中英

Add properties to an array of objects from a separate array

I need to add properties to an array of objects from a separate array. I have 2 arrays. The first array is an array of objects. The second array is an array of Ints. I want to add a new property to each object in the array from the array of Ints.

Example:

var arrOfObj = [
  {
    name: "eve"
  },
  {
    name: "john"
  },
  {
    name: "jane"
  }
];

var arr = [0, 1, 2]
//Desired output

var arrOfObj = [
  {
    name: "eve",
    num: 0
  },
  {
    name: "john",
    num: 1
  },
  {
    name: "jane",
    num: 2
  }
];

Thanks for the help!

You could do with Array#forEach

 var arrOfObj = [ { name: "eve" }, { name: "john" }, { name: "jane" }]; var arr = [0, 1, 2]; arrOfObj.forEach((a,i)=>{ a.num = arr[i]}); console.log(arrOfObj)

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