Object for a javascript array

Asked

Viewed 48 times

0

I have an object with the following values:

let sel = { 
    "1": { "id_turma": 485, "codigo_turma": "1112A - 41", "ano_ciclo": 14 }, 
    "2": { "id_turma": 486, "codigo_turma": "1112B - 27", "ano_ciclo": 18 }, 
    "3": { "id_turma": 487, "codigo_turma": "1112C - 24", "ano_ciclo": 14 }
}

I need to turn into an array like this:

valor['1112A'] => 14
valor['1112B'] => 18
valor['1112C'] => 14

I tried so:

let val = []

sel.forEach(function(ix) {
    if(ix.value) {
        val[ix.value] = ix.ano_ciclo
    }
})

It’s not working out

  • And numbers 41, 27 and 24 in codigo_turma? Must be ignored?

  • @Andersoncarloswoss are just information. They should be ignored

3 answers

5


To use the forEach, your object needs to be an array [], as it is an object of objects, you can use the Object.() for that reason:

let sel = { 
    "1": { "id_turma": 485, "codigo_turma": "1112A - 41", "ano_ciclo": 14 }, 
    "2": { "id_turma": 486, "codigo_turma": "1112B - 27", "ano_ciclo": 18 }, 
    "3": { "id_turma": 487, "codigo_turma": "1112C - 24", "ano_ciclo": 14 }
}

let  valor = [];

Object.entries(sel).forEach(([o, v]) => {
    valor[v.codigo_turma.substring(0,5)] = v.ano_ciclo;
});

console.log(valor["1112A"]);
console.log(valor["1112B"]);
console.log(valor["1112C"]);

3

Another way is using the map, see how it would look:

let sel = { 
    "1": { "id_turma": 485, "codigo_turma": "1112A - 41", "ano_ciclo": 14 }, 
    "2": { "id_turma": 486, "codigo_turma": "1112B - 27", "ano_ciclo": 18 }, 
    "3": { "id_turma": 487, "codigo_turma": "1112C - 24", "ano_ciclo": 14 }
}

sel = Object.keys(sel).map(key =>
    ({ [sel[key].codigo_turma.split('-')[0].trim()]: sel[key].ano_ciclo })
);

console.log(sel);

2

let sel = {
  "1": {
    "id_turma": 485,
    "codigo_turma": "1112A - 41",
    "ano_ciclo": 14
  },
  "2": {
    "id_turma": 486,
    "codigo_turma": "1112B - 27",
    "ano_ciclo": 18
  },
  "3": {
    "id_turma": 487,
    "codigo_turma": "1112C - 24",
    "ano_ciclo": 14
  }
};

let val = [];

Object.values(sel).forEach(function(ix) {
  val[ix.codigo_turma.split(' ')[0]] = ix.ano_ciclo
});

console.log('val[\'1112A\']:', val['1112A']);
console.log('val[\'1112B\']:', val['1112B']);
console.log('val[\'1112C\']:', val['1112C']);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.