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

102
Visualizações
how to insert deep in object

I have this object with tables:

let tables = {
  "2021-08-25": {
    "B0705": {
      "48": "heaven"
    },
    "B0704": {
      "48": "hell"
    }
  }
}

An I would like to insert dynamicly a new table. I tried this:

var insertTable = (date,table,slot) => {
  let newDesk = {
      [date]: {
        [table]: {
          [slot]: 'slotter'
        }
      }
  };
  Object.assign(tables,newDesk);
};

But it overwrites my exsiting entrances.

This will also not work:

  var insertTable2 = (date,table,slot) => {
    Object.defineProperty(tables, date, {
      table: {slot: 'slotter'}
    });
  };

How this will work?

insertTable2("2021-08-25","B0705","22");
insertTable2("2021-08-25","B0705","12");
insertTable2("2021-08-25","B0706","33");
insertTable2("2021-08-26","B0703","11");
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

For a more reusable solution, take a look at this SO question - you want to deep merge the new object with the old one, not shallowly merge them.

A non reusable solution can be built like this (to illustrate that for more complex paths/requirements the above solution is much easier):

let tables = {
  "2021-08-25": {
    "B0705": {
      "48": "heaven"
    },
    "B0704": {
      "48": "hell"
    }
  }
}
// this will mutate the tables object
const insertTable = (date, table, slot) => {
  // is there an object with this date yet? if not create it.
  if(typeof tables[date] === "undefined"){
    tables[date] = {};
  }
  // is there an object with this table yet? if not create it.
  if(typeof tables[date][table] === "undefined"){
    tables[date][table] = {};
  }
  // set the value now that we know all intermediate objects are defined.
  tables[date][table][slot] = "slotter";
  
  
}
console.log(tables);
insertTable("2021-08-25","B0705","22");
insertTable("2021-08-25","B0705","12");
insertTable("2021-08-25","B0706","33");
insertTable("2021-08-26","B0703","11");

console.log(tables);

about 4 years ago · Juan Pablo Isaza Relatório

0

You could use an array to express the object path you wish the value to be placed at, also specifying the value to be set at the path.

We'd then use Array.reduce() to navigate down the path and eventually set the value at the last path element:

let tables = {
  "2021-08-25": {
    "B0705": {
      "48": "heaven"
    },
    "B0704": {
      "48": "hell"
    }
  }
}

function insertTable(table, path, value) {
    path.reduce((acc, pathElement, idx) => {
        if (idx < path.length -1) {
            // We're not at the final element of path, add a new object if necessary
            if (!acc[pathElement]) acc[pathElement] = {};
        } else {
            // We're at the last pathElement, set the value, e.g. 'slotter'
            acc[pathElement] = value;
        }
        return acc[pathElement];
    }, table)
}

insertTable(tables, ['2021-08-25', 'B0705', '22'], 'slotter');
insertTable(tables, ['2021-08-25', 'B0705', '12'], 'slotter');
insertTable(tables, ['2021-08-25', 'B0706', '33'], 'some value');
insertTable(tables, ['2021-08-26', 'B0703', '11'], 'another value');

console.log(tables)

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