How to extract values from fields of a javascript object (JSON)?

Asked

Viewed 753 times

1

I have any Javascript object, ex:

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 got the following way:

Object.keys(pessoa);

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

Now I need a way to list only the values of the fields..

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

would be something like Object.values(person), but it doesn’t have this method...

How can I do that?

  • I think it might help you. http://answall.com/questions/127924/percorrer-um-array-sem-saber-seus-indices/127926#127926

2 answers

1


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

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

You can also use a 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 mootools library we have that 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;
},
  • 1

    Cool @Sergio, that’s just what I needed, thank you very much!

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]);      
}

Browser other questions tagged

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