Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get property name and value from array

so i have object that have many properties, i need to get all values and property names from that object, i'm not sure what is best and easiest way to do it. I already tried few methods but didn't had any luck with it

angular.forEach(array, function(value, key){
   console.log(value);
});
like image 661
Sahbaz Avatar asked Dec 01 '16 09:12

Sahbaz


2 Answers

You can also use the Object.keys() which returns an array of the keys of the object. For instance :

var obj = { 0 : "a", 1 : "b", 2 : "c"};
console.log(Object.keys(obj)); // [0, 1, 2]

You can also use the Object.values() which returns an array of the values of an object :

var obj = { 0 : "a", 1 : "b", 2 : "c"};
console.log(Object.values(obj)); // ['a', 'b', 'c']
like image 84
Dimitri Avatar answered Oct 28 '22 19:10

Dimitri


forEach works with arrays, for object properties you need:

for (var property in object) {
    if (object.hasOwnProperty(property)) {
        console.log(property, ' ', object[property]);
    }
}
like image 37
Luis Sieira Avatar answered Oct 28 '22 19:10

Luis Sieira