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!

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];
}
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

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)

Comments

Your Answer

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