I've an array with some values and I want to add a new element to this array.
I have an array like this:
arr1 = [
{'id': '1', 'data': 'data1'},
{'id': '2', 'data': 'data2'}
]
val = ['value1','value2']
and I want to add val array in arr1 and make a new array like this:
arr1 = [
{'id': '1', 'data': 'data1', 'val': 'value1'},
{'id': '2', 'data': 'data2', 'val': 'value2'}
]
How can I do that ?
I'm new to Javascript, so any type of help can be appreciated. Thank you!
3 Answers 3
Iterate over either array via a for loop or Array#forEach. Use the loop variable to access the elements of both arrays and create the new property by assigning to it:
for (var i = 0; i < arr1.length; i++) {
arr1[i].val = val[i];
}
Comments
arr1.forEach((item, index) => {
item.val = val[index]
})
This will iterate over each item in the array and add the new property to each, referencing the indices in the val array to get the proper value.
Homework: Array.prototype.forEach
Comments
const arr1 = [{
'id': '1',
'data': 'data1'
},
{
'id': '2',
'data': 'data2'
}
]
const val = ['value1', 'value2']
const res = arr1.map((el, index) => ({ ...el,
val: val[index]
}))
console.log(res)