I tried to do basic things. I have an array that contains multiple objects. I want to add new key-value pair in every array object.
I tried this by following code.
exports.addBuyOption = (arr) => {
var newArr=arr;
return new Promise((resolve, reject) => {
for (let i = 0; i < newArr.length; i++) {
newArr[i].name="new name" //updating the existing key value
newArr[i].canBuy=true //new key value
}
setTimeout(() => {
resolve(newArr);
}, 2000)
})
}
I added set timeout as I just wanted to confirm whether the promise returned after the loop operation or not. Also when code does not run with the origin array then I make a new variable with newArr name but the code also does not work.
exports.addBuyOption = (arr) => {
return new Promise((resolve, reject) => {
for (let i = 0; i < arr.length; i++) {
arr[i].name="new name" //updating the existing key value
arr[i].canBuy=true //new key value
}
resolve(arr);
})
}
With this code, I was able to update my existing key-value but was not able to add any new key value. What am I doing wrong? I tried to change the method of adding key from dot operator to array indexing to Object.assign but none of them worked for me.