How to create javascript array object within a FOR?

Asked

Viewed 521 times

0

I need to pass an array object as follows, to the api:

[paulo = 1, gustavo = 2, amanda = 3,...]

I have the following code:

$scope.salvarHabilidades = function(pro){

    var valores = pro.filter(function(o,i){
        return o.habilidades == true;
    });

    var habi = new Array();

    for(var i = 0; i < valores.length; i++){
        console.log(valores[i]);
        habi = [(valores[i].descricao = valores[i].idhabilidade)];
    }
    habi.idusuario = $rootScope.idPro;
    console.log(habi);

}

For what appears in the console line "console.log(values[i])" is this:inserir a descrição da imagem aqui

Follow the selection screen:

inserir a descrição da imagem aqui

  • [paulo = 1, gustavo = 2, amanda = 3,...] is not a valid array, each input will get the value of the assignment. It was not clear to me the format you need..

  • The @Lucascosta is right. This: [paulo = 1, Gustavo = 2, Amanda = 3,...] is not an object notation and much less an array notation. The closest you could get to an array notation would be: ["paulo = 1", "Gustavo = 2", "Amanda = 3",...]. But that’s definitely not what you want!

  • I need the number to be assigned to the name. It may be that the example I gave is not a valid array, but I need to mount in a way that is. They understood?

  • Let it be ["paul" = 1, "Gustav" = 2, ...]

  • A legal structure would be [ {"name": "paul", "value": 1}] for me

  • Could you clarify your question a little, Gustavo? for example: What are numerical values? Skills Ids? If so, a person could own 2 or more?

  • Yes, this @Lucascosta! .

  • @Gustavosevero And what would be the relationship with skills?

  • In place of the name go skills, @Onosendai.

Show 4 more comments

1 answer

2

Could store objects in array using Array#map:

var habi = [];
var valores = [{
  "idhabilidade": 1,
  "descricao": "Descricao 1"
}, {
  "idhabilidade": 2,
  "descricao": "Descricao 2"
}]

habi = valores.map(function(item) {
  return {
    "nome": item.descricao,
    "valor": item.idhabilidade
  }
})

console.log(habi);

  • In parts, it worked, BUT, I selected 3 abilities and appeared only 1 on the console. Need to insert more data into this object as it runs FOR, understand?

  • This part is beyond what you presented in the question @Gustavosevero

  • What else do I need to report? In the question, title, put it was within a FOR, so much so that the FOR is in the code.

  • I selected 3 abilities and appeared only 1 on the console, selected where?

  • I’m sorry, I just put it in the description of doubt, Lucas.

  • I selected from a screen with a checkbox list.

  • Any idea Lucas?

Show 2 more comments

Browser other questions tagged

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