How to move an object in javascript?

6

How to scroll through the object below with javascript? (in the same way that the arrays are run with the map ()).

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"
};
    
asked by anonymous 23.12.2016 / 19:30

3 answers

7

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

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.entries :

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

for (var [key, value] of Object.entries(obj)) {
    console.log(key + ' ' + value);
}
    
23.12.2016 / 19:33
3

Correct is to use for in with property checking 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 some Object has any change in Prototype it will be passed in 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
    
23.12.2016 / 19:38
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...
});
    
23.12.2016 / 19:36