How to browse an object in Javascript?

Asked

Viewed 24,684 times

11

How to navigate the object below with Javascript?

var obj = {
  "column01": "Coluna 01",
  "column02": "Coluna 02",
  "column03": "Coluna 03",
  "column04": "Coluna 04",
  "column05": "Coluna 05",
  "column06": "Coluna 06",
  "column07": "Coluna 07",
  "column08": "Coluna 08",
  "column09": "Coluna 09",
  "column10": "Coluna 10"
};

3 answers

19


You can use Object.Keys or for. in to iterate keys and object values:

var obj = {
  "column01": "Coluna 01",
  "column02": "Coluna 02"
};

Object.keys(obj).forEach(function(item){
 console.log(item + " = " + obj[item]);
});

for (var property in obj){
  console.log(property + " = " + obj[property]);
}

Or with Object.:

var obj = {
  "column01": "Coluna 01",
  "column02": "Coluna 02"
};

for (var [key, value] of Object.entries(obj)) {
    console.log(key + ' ' + value);
}

  • 4

    +1 for the special summary [ ] in combination with for... of.

5

It is right to use for in with property check to avoid possible errors. Example:

var obj = {
    "column01": "Coluna 01",
    "column02": "Coluna 02",
    "column03": "Coluna 03"
};

for (var column in obj) {
    obj.hasOwnProperty(column) {
        console.log(column); // column01
        console.log(obj[column]); // Coluna 01
    }
}

Why use obj.hasOwnProperty?

If by chance any Object has any changes in the Prototype will be passed in the for. Example:

Object.prototype.test = function() {};
Object.prototype.test2 = function() {};

var obj = {
    "a": 1,
    "b": 2
};

for (var letter in obj) {
    console.log(letter);
}

// a
// b
// test
// test2

1

You can make use of Object.Keys, for example:

Object.keys(obj).forEach((key) => {
    console.log(key); //column01...
    console.log(obj[key]); //Coluna 01...
});

Browser other questions tagged

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