1

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!

asked Mar 22, 2019 at 20:42
0

3 Answers 3

2

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];
}
answered Mar 22, 2019 at 20:45
Sign up to request clarification or add additional context in comments.

Comments

2
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

answered Mar 22, 2019 at 20:47

Comments

1

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)

answered Mar 22, 2019 at 20:49

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.