Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

237
Visualizações
How to add key value pair in array of Mongoose response in JavaScript

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.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

With this code, I was able to update my existing key-value but was not able to add any new key value.

The only explanation for that would be that the objects in the array have had Object.preventExtensions applied to them. Here's an example:

function addBuyOption(arr) {
    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 
    }
    return arr;
}

const arr = [
    {name: "old name 1"},
    {name: "old name 2"},
    {name: "old name 3"},
].map(Object.preventExtensions);
console.log("Before:");
console.log(JSON.stringify(arr, null, 4));
addBuyOption(arr);
console.log("After:");
console.log(JSON.stringify(arr, null, 4));
.as-console-wrapper {
    max-height: 100% !important;
}

(Note I did away with the promise, it doesn't do anything useful in this code.)

If that's what's going on, you can't add properties to the objects. But you can create a new array with copies of the objects with the new property:

function addBuyOption(arr) {
    return arr.map(obj => ({
        ...obj,           // Copy existing properties
        name: "new name", // Set new value for existing property
        canBuy: true,     // Set new property
    }));
}

const arr = [
    {id: 1, name: "old name 1"},
    {id: 2, name: "old name 2"},
    {id: 3, name: "old name 3"},
].map(Object.preventExtensions);
console.log("Before:");
console.log(JSON.stringify(arr, null, 4));
const newArr = addBuyOption(arr);
console.log("After:");
console.log(JSON.stringify(newArr, null, 4));
.as-console-wrapper {
    max-height: 100% !important;
}

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda