-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAddObjOnArray.js
More file actions
30 lines (27 loc) · 1020 Bytes
/
AddObjOnArray.js
File metadata and controls
30 lines (27 loc) · 1020 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
/**
* Version ES5
* Function to add (complete) the same object in an array of objects
* @param{array} array that contains objects
* @param{object} object to add in array of objects
* @return{array} return array of objects completed
*/
function addObjOnArray(arr, obj) {
var add = Object.keys(obj);
for (var i = 0; i < arr.length; i++) {
for (var j in add){
arr[i][add[j]] = obj[add[j]];
}
}
return arr;
}
/**
* Version ES6 with spread operator
* Function to add (complete) the same object in an array of objects
* @param{array} array that contains objects
* @param{object} object to add in array of objects
* @return{array} return array of objects completed
*/
const addObjOnArray2 = (arr, obj) => [...arr, obj];
var tab = [{name : 'Romain', hoobies : 'rock climbing'}, {name:'Max', hoobies:'Lego'}];
var obj1 = {city : 'Toulouse'};
console.log(addObjOnArray(tab, obj1)); // return [{name:"Romain", hoobies:"rock climbing", city:"Toulouse"}, {name:"Max", hoobies:"Lego", city:"Toulouse"}]