How do I extract the field values from a javascript Object (JSON)?

1

I have a Javascript object, eg:

var pessoa = {nome: 'Carlos', cpf: '123', rg: '456'};

I need to list the fields that this Object has and the corresponding values.

  

To list the fields I have achieved the following:

Object.keys(pessoa);

//Saída no Console..
 nome
 cpf
 rg
  

Now I need a way to list only field values.

//a saída deve ser assim..
  Carlos
  123
  456

would be something like Object.values (person), but it does not have this method ...

How can I do this?

    
asked by anonymous 16.05.2016 / 18:44

2 answers

1

You have to use a loop, if you need this in an array you can do this:

Object.keys(pessoa).map(function(prop){ return pessoa[prop];});
// que dá ["Carlos", "123", "456"]

You can also use for in , but it will be like Object.keys, a key iterator:

for (var prop in pessoa){
    console.log(prop, pessoa[prop]);
}
// que dá : 
// nome Carlos
// cpf 123
// rg 456

Interestingly in the MooTools library we have this method. The implementation is like this :

values: function(object){
    var values = [];
    var keys = Object.keys(object);
    for (var i = 0; i < keys.length; i++){
        var k = keys[i];
        values.push(object[k]);
    }
    return values;
},
    
16.05.2016 / 18:51
0

You can use a loop and put everything in another array:

var data = [{"nome":"Eduardo","cpf":"00.666.999-33"},
{"nome":"Paulo","cpf":"222.222.666-33"}];



var nomes = [];
for(i = 0; i< data.length; i++){    
    if(nomes.indexOf(data[i].nome) === -1){
        nomes.push(data[i].nome);        
    }        
}

for(i = 0; i< nomes.length; i++){    
    alert(nomes[i]);      
}
    
16.05.2016 / 18:59