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

110
Visualizações
Convert array to object by concatenating values under same key

I tried searching through previous questions but couldn't find the answer so here's a very generic question.

I have a multidimensional array like so:

array = [
    [ "1", "2013-14" , 1234],​​
    [ "2", "2013-14", 2345],
    [ "1", "2014-15" , 5234],​​
    [ "2", "2014-15", 7345],
]

I am trying to change it to a nested object based on the year:

obj = {
  "2013-14": { 1: "1234", 2: "2345" },
  "2014-15": { 2: "5234", 2: "7345" }
}

I tried this, which gave a similar but wrong solution:

let obj = {}
for (let i = 0; i < array.length; i++) {
  obj[array[i][1]] = {
    [array[i][0]]: array[i][2]
  }
}

the solution I got:

obj = {
      "2013-14": { 2: "2345" },
      "2014-15": { 2: "7345" }
}

so instead of concatenating values under the same key, which in this case is the year, it is overriding it and saving the last one

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

0

You need to respect the object for ech date.

const
    array = [["1", "2013-14", 1234], ["2", "2013-14", 2345], ["1", "2014-15", 5234], ["2", "2014-15", 7345]],
    obj = {};
    
for (let i = 0; i < array.length; i++) {
    obj[array[i][1]] ??= {};
    obj[array[i][1]][array[i][0]] = array[i][2];
}

console.log(obj);

A shorter approach with destructuring

const
    array = [["1", "2013-14", 1234], ["2", "2013-14", 2345], ["1", "2014-15", 5234], ["2", "2014-15", 7345]],
    obj = {};
    
for (const [inner, outer, value] of array) {
    obj[outer] ??= {};
    obj[outer][inner] = value;
}

console.log(obj);

about 4 years ago · Juan Pablo Isaza Relatório

0

The problem I think is that you're trying to access objects within the key you just initialised. The code is writing the data you wanted but since you're accessing the same key multiple times, the data is being overwritten.

I tried the following approach in Python and it worked :

data = [
[ "1", "2013-14" , 1234],
[ "2", "2013-14", 2345],
[ "1", "2014-15" , 5234],
[ "2", "2014-15", 7345],
]

# EXTRACT KEYS TO INITIALIZE OBJECT AND INSERT VALUES LATER
keys=[]
for i in data :
    if i[1] not in keys:
        keys.append(i[1]) 
parsed_obj = {k:{} for k in keys}

for i in data :
    parsed_obj[i[1]][i[0]] = i[2]
print(parsed_obj)

Output :

{'2013-14': {'1': 1234, '2': 2345}, '2014-15': {'1': 5234, '2': 7345}}

I know it's not ideal but maybe someone can help you translate this into JS.

about 4 years ago · Juan Pablo Isaza Relatório

0

you can use spread operator {...} to concat it.

Here is the code:

var array = [
  ["1", "2013-14", 1234],
  ["2", "2013-14", 2345],
  ["1", "2014-15", 5234],
  ["2", "2014-15", 7345],
];

let obj = {};
for (let i = 0; i < array.length; i++) {
  obj[array[i][1]] = { ...obj[array[i][1]], [array[i][0]]: array[i][2] };
}

console.log(obj);

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