I have a JavaScript object like the following:
var p = {
"p1": "value1",
"p2": "value2",
"p3": "value3"
};
How do I loop through all of p's elements (p1, p2, p3...) and get their keys and values?
I have a JavaScript object like the following:
var p = {
"p1": "value1",
"p2": "value2",
"p3": "value3"
};
How do I loop through all of p's elements (p1, p2, p3...) and get their keys and values?
You can use the for-in loop as shown by others. However, you also have to make sure that the key you get is an actual property of an object, and doesn't come from the prototype.
Here is the snippet:
var p = {
"p1": "value1",
"p2": "value2",
"p3": "value3"
};
for (var key in p) {
if (p.hasOwnProperty(key)) {
console.log(key + " -> " + p[key]);
}
}
For-of with Object.keys() alternative:
var p = {
0: "value1",
"b": "value2",
key: "value3"
};
for (var key of Object.keys(p)) {
console.log(key + " -> " + p[key])
}
Notice the use of for-of instead of for-in, if not used it will return undefined on named properties, and Object.keys() ensures the use of only the object's own properties without the whole prototype-chain properties
Using the new Object.entries() method:
Note: This method is not supported natively by Internet Explorer. You may consider using a Polyfill for older browsers.
const p = {
"p1": "value1",
"p2": "value2",
"p3": "value3"
};
for (let [key, value] of Object.entries(p)) {
console.log(`${key}: ${value}`);
}
You have to use the for-in loop
But be very careful when using this kind of loop, because this will loop all the properties along the prototype chain.
Therefore, when using for-in loops, always make use of the hasOwnProperty method to determine if the current property in iteration is really a property of the object you're checking on:
for (var prop in p) {
if (!p.hasOwnProperty(prop)) {
//The current property is not a direct property of p
continue;
}
//Do your logic with the property here
}
Preface:
Here in 2018, your options for looping through an object's properties are (some examples follow the list):
for-in [MDN, spec] — A loop structure that loops through the names of an object's enumerable properties, including inherited ones, whose names are stringsObject.keys [MDN, spec] — A function providing an array of the names of an object's own, enumerable properties whose names are strings.Object.values [MDN, spec] — A function providing an array of the values of an object's own, enumerable properties.Object.entries [MDN, spec] — A function providing an array of the names and values of an object's own, enumerable properties (each entry in the array is a [name, value] array).Object.getOwnPropertyNames [MDN, spec] — A function providing an array of the names of an object's own properties (even non-enumerable ones) whose names are strings.Object.getOwnPropertySymbols [MDN, spec] — A function providing an array of the names of an object's own properties (even non-enumerable ones) whose names are Symbols.Reflect.ownKeys [MDN, spec] — A function providing an array of the names of an object's own properties (even non-enumerable ones), whether those names are strings or Symbols.Object.getPrototypeOf [MDN, spec] and use Object.getOwnPropertyNames, Object.getOwnPropertySymbols, or Reflect.ownKeys on each object in the prototype chain (example at the bottom of this answer).With all of them except for-in, you'd use some kind of looping construct on the array (for, for-of, forEach, etc.).
Examples:
for-in:
// A prototype object to inherit from, with a string-named property
const p = {answer: 42};
// The object we'll look at, which inherits from `p`
const o = Object.create(p);
// A string-named property
o.question = "Life, the Universe, and Everything";
// A symbol-named property
o[Symbol("author")] = "Douglas Adams";
for (const name in o) {
const value = o[name];
console.log(`${name} = ${value}`);
}
Object.keys (with a for-of loop, but you can use any looping construct):
// A prototype object to inherit from, with a string-named property
const p = {answer: 42};
// The object we'll look at, which inherits from `p`
const o = Object.create(p);
// A string-named property
o.question = "Life, the Universe, and Everything";
// A symbol-named property
o[Symbol("author")] = "Douglas Adams";
for (const name of Object.keys(o)) {
const value = o[name];
console.log(`${name} = ${value}`);
}
Object.values:
// A prototype object to inherit from, with a string-named property
const p = {answer: 42};
// The object we'll look at, which inherits from `p`
const o = Object.create(p);
// A string-named property
o.question = "Life, the Universe, and Everything";
// A symbol-named property
o[Symbol("author")] = "Douglas Adams";
for (const value of Object.values(o)) {
console.log(`${value}`);
}
Object.entries:
// A prototype object to inherit from, with a string-named property
const p = {answer: 42};
// The object we'll look at, which inherits from `p`
const o = Object.create(p);
// A string-named property
o.question = "Life, the Universe, and Everything";
// A symbol-named property
o[Symbol("author")] = "Douglas Adams";
for (const [name, value] of Object.entries(o)) {
console.log(`${name} = ${value}`);
}
Object.getOwnPropertyNames:
// A prototype object to inherit from, with a string-named property
const p = {answer: 42};
// The object we'll look at, which inherits from `p`
const o = Object.create(p);
// A string-named property
o.question = "Life, the Universe, and Everything";
// A symbol-named property
o[Symbol("author")] = "Douglas Adams";
for (const name of Object.getOwnPropertyNames(o)) {
const value = o[name];
console.log(`${name} = ${value}`);
}
Object.getOwnPropertySymbols:
// A prototype object to inherit from, with a string-named property
const p = {answer: 42};
// The object we'll look at, which inherits from `p`
const o = Object.create(p);
// A string-named property
o.question = "Life, the Universe, and Everything";
// A symbol-named property
o[Symbol("author")] = "Douglas Adams";
for (const name of Object.getOwnPropertySymbols(o)) {
const value = o[name];
console.log(`${String(name)} = ${value}`);
}
Reflect.ownKeys:
// A prototype object to inherit from, with a string-named property
const p = {answer: 42};
// The object we'll look at, which inherits from `p`
const o = Object.create(p);
// A string-named property
o.question = "Life, the Universe, and Everything";
// A symbol-named property
o[Symbol("author")] = "Douglas Adams";
for (const name of Reflect.ownKeys(o)) {
const value = o[name];
console.log(`${String(name)} = ${value}`);
}
All properties, including inherited non-enumerable ones:
// A prototype object to inherit from, with a string-named property
const p = {answer: 42};
// The object we'll look at, which inherits from `p`
const o = Object.create(p);
// A string-named property
o.question = "Life, the Universe, and Everything";
// A symbol-named property
o[Symbol("author")] = "Douglas Adams";
for (let depth = 0, current = o; current; ++depth, current = Object.getPrototypeOf(current)) {
for (const name of Reflect.ownKeys(current)) {
const value = o[name];
console.log(`[${depth}] ${String(name)} = ${String(value)}`);
}
}
.as-console-wrapper {
max-height: 100% !important;
}
You can just iterate over it like:
for (var key in p) {
alert(p[key]);
}
Note that key will not take on the value of the property, it's just an index value.
In ECMAScript 5 you have new approach in iteration fields of literal - Object.keys
More information you can see on MDN
My choice is below as a faster solution in current versions of browsers (Chrome30, IE10, FF25)
var keys = Object.keys(p),
len = keys.length,
i = 0,
prop,
value;
while (i < len) {
prop = keys[i];
value = p[prop];
i += 1;
}
You can compare performance of this approach with different implementations on jsperf.com:
Browser support you can see on Kangax's compat table
For old browser you have simple and full polyfill
UPD:
performance comparison for all most popular cases in this question on perfjs.info:
Today 2020.03.06 I perform tests of chosen solutions on Chrome v80.0, Safari v13.0.5 and Firefox 73.0.1 on MacOs High Sierra v10.13.6
for-in (A,B) are fast (or fastest) for all browsers for big and small objectsfor-of (H) solution is fast on chrome for small and big objectsi (J,K) are quite fast on all browsers for small objects (for firefox also fast for big ojbects but medium fast on other browsers)Performance tests was performed for
Below snippets presents used solutions
function A(obj,s='') {
for (let key in obj) if (obj.hasOwnProperty(key)) s+=key+'->'+obj[key] + ' ';
return s;
}
function B(obj,s='') {
for (let key in obj) s+=key+'->'+obj[key] + ' ';
return s;
}
function C(obj,s='') {
const map = new Map(Object.entries(obj));
for (let [key,value] of map) s+=key+'->'+value + ' ';
return s;
}
function D(obj,s='') {
let o = {
...obj,
*[Symbol.iterator]() {
for (const i of Object.keys(this)) yield [i, this[i]];
}
}
for (let [key,value] of o) s+=key+'->'+value + ' ';
return s;
}
function E(obj,s='') {
let o = {
...obj,
*[Symbol.iterator]() {yield *Object.keys(this)}
}
for (let key of o) s+=key+'->'+o[key] + ' ';
return s;
}
function F(obj,s='') {
for (let key of Object.keys(obj)) s+=key+'->'+obj[key]+' ';
return s;
}
function G(obj,s='') {
for (let [key, value] of Object.entries(obj)) s+=key+'->'+value+' ';
return s;
}
function H(obj,s='') {
for (let key of Object.getOwnPropertyNames(obj)) s+=key+'->'+obj[key]+' ';
return s;
}
function I(obj,s='') {
for (const key of Reflect.ownKeys(obj)) s+=key+'->'+obj[key]+' ';
return s;
}
function J(obj,s='') {
let keys = Object.keys(obj);
for(let i = 0; i < keys.length; i++){
let key = keys[i];
s+=key+'->'+obj[key]+' ';
}
return s;
}
function K(obj,s='') {
var keys = Object.keys(obj), len = keys.length, i = 0;
while (i < len) {
let key = keys[i];
s+=key+'->'+obj[key]+' ';
i += 1;
}
return s;
}
function L(obj,s='') {
Object.keys(obj).forEach(key=> s+=key+'->'+obj[key]+' ' );
return s;
}
function M(obj,s='') {
Object.entries(obj).forEach(([key, value]) => s+=key+'->'+value+' ');
return s;
}
function N(obj,s='') {
Object.getOwnPropertyNames(obj).forEach(key => s+=key+'->'+obj[key]+' ');
return s;
}
function O(obj,s='') {
Reflect.ownKeys(obj).forEach(key=> s+=key+'->'+obj[key]+' ' );
return s;
}
// TEST
var p = {
"p1": "value1",
"p2": "value2",
"p3": "value3"
};
let log = (name,f) => console.log(`${name} ${f(p)}`)
log('A',A);
log('B',B);
log('C',C);
log('D',D);
log('E',E);
log('F',F);
log('G',G);
log('H',H);
log('I',I);
log('J',J);
log('K',K);
log('L',L);
log('M',M);
log('N',N);
log('O',O);
This snippet only presents choosen solutions
And here are result for small objects on chrome
for(key in p) {
alert( p[key] );
}
Note: you can do this over arrays, but you'll iterate over the length and other properties, too.
Single line and more readable code can be..
Object.entries(myObject).map(([key, value]) => console.log(key, value))
You can also use Object.keys() and iterate over the object keys like below to get the value:
var p = {
"p1": "value1",
"p2": "value2",
"p3": "value3"
};
Object.keys(p).forEach((key)=> {
console.log(key +' -> '+ p[key]);
});
Using a for-of on Object.keys()
Like:
let object = {
"key1": "value1",
"key2": "value2",
"key3": "value3"
};
for (let key of Object.keys(object)) {
console.log(key + " : " + object[key])
}
In latest ES script, you can do something like this:
let p = {foo: "bar"};
for (let [key, value] of Object.entries(p)) {
console.log(key, value);
}
The Object.keys() method returns an array of a given object's own enumerable properties. Read more about it here
var p = {
"p1": "value1",
"p2": "value2",
"p3": "value3"
};
Object.keys(p).map((key)=> console.log(key + "->" + p[key]))
Multiple way to iterate object in javascript
Using for...in loop
var p = {
"p1": "value1",
"p2": "value2",
"p3": "value3"
};
for (let key in p){
if(p.hasOwnProperty(key)){
console.log(`${key} : ${p[key]}`)
}
}
Using for...of loop
var p = {
"p1": "value1",
"p2": "value2",
"p3": "value3"
};
for (let key of Object.keys(p)){
console.log(`key: ${key} & value: ${p[key]}`)
}
Using forEach() with Object.keys, Object.values, Object.entries
var p = {
"p1": "value1",
"p2": "value2",
"p3": "value3"
};
Object.keys(p).forEach(key=>{
console.log(`${key} : ${p[key]}`);
});
Object.values(p).forEach(value=>{
console.log(value);
});
Object.entries(p).forEach(([key,value])=>{
console.log(`${key}:${value}`)
})
A good way for looping on an enumerable JavaScript object which could be awesome and common for ReactJS is using Object.keys or Object.entries with using map function. like below:
// assume items:
const items = {
first: { name: 'phone', price: 400 },
second: { name: 'tv', price: 300 },
third: { name: 'sofa', price: 250 },
};
For looping and show some UI on ReactJS act like below:
~~~
<div>
{Object.entries(items).map(([key, ({ name, price })]) => (
<div key={key}>
<span>name: {name}</span>
<span>price: {price}</span>
</div>
))}
</div>
Actually, I use the destructuring assignment twice, once for getting key once for getting name and price.
Object.entries(myObject).map(([key, value]) => console.log(key, value))
You can try like this. myObject will be {name: "", phone: ""} so and so, this will generate key and value. So key here is name, phone and value are like dog, 123123.
Example {name: "dog"}
Here key is name and value is dog.
var p =[{"username":"ordermanageadmin","user_id":"2","resource_id":"Magento_Sales::actions"},
{"username":"ordermanageadmin_1","user_id":"3","resource_id":"Magento_Sales::actions"}]
for(var value in p) {
for (var key in value) {
if (p.hasOwnProperty(key)) {
console.log(key + " -> " + p[key]);
}
}
}
since ES06 you can get the values of an object as array with
let arrValues = Object.values( yourObject) ;
it return the an array of the object values and it not extract values from Prototype!!
and for keys ( allready answerd before me here )
let arrKeys = Object.keys(yourObject);
Pass your object to Object.keys(). This will return an array containing all the keys in the object. You can then loop through the array using map. Using obj[key] where obj is your object and key is the current value in the map iteration, you can get the value for that key/property.
const obj = { name: "Jane", age: 50 };
Object.keys(obj).map( key => {
console.log(key, obj[key]);
});
Using for...in and Object hasOwnProperty
var p = {
"p1": "value1",
"p2": "value2",
"p3": "value3"
};
for (var key in p) {
if (p.hasOwnProperty(key)) {
console.log(key, ' : ', p[key]);
}
}
Using for...of and Object keys
var p = {
"p1": "value1",
"p2": "value2",
"p3": "value3"
};
for (var key of Object.keys(p)) {
console.log(key, " : ", p[key])
}
Using Object keys and forEach
var p = {
"p1": "value1",
"p2": "value2",
"p3": "value3"
};
Object.keys(p).forEach(function(key) {
console.log(key, ' : ', p[key]);
});
Using for...of and Object entries
var p = {
"p1": "value1",
"p2": "value2",
"p3": "value3"
};
for (let [key, value] of Object.entries(p)) {
console.log(key, ' : ', value);
}
Using Object entries and forEach
var p = {
"p1": "value1",
"p2": "value2",
"p3": "value3"
};
Object.entries(p).forEach(([key, value]) => console.log(key, ' : ', value));
Object.entries() function:
var p = {
"p1": "value1",
"p2": "value2",
"p3": "value3"
};
for (var i in Object.entries(p)){
var key = Object.entries(p)[i][0];
var value = Object.entries(p)[i][1];
console.log('key['+i+']='+key+' '+'value['+i+']='+value);
}
I had a similar problem when using Angular, here is the solution that I've found.
Step 1. Get all the object keys. using Object.keys. This method returns an array of a given object’s own enumerable properties.
Step 2. Create an empty array. This is an where all the properties are going to live, since your new ngFor loop is going to point to this array, we gotta catch them all. Step 3. Iterate throw all keys, and push each one into the array you created. Here’s how that looks like in code.
// Evil response in a variable. Here are all my vehicles.
let evilResponse = {
"car" :
{
"color" : "red",
"model" : "2013"
},
"motorcycle":
{
"color" : "red",
"model" : "2016"
},
"bicycle":
{
"color" : "red",
"model" : "2011"
}
}
// Step 1. Get all the object keys.
let evilResponseProps = Object.keys(evilResponse);
// Step 2. Create an empty array.
let goodResponse = [];
// Step 3. Iterate throw all keys.
for (prop of evilResponseProps) {
goodResponse.push(evilResponseProps[prop]);
}
Here is a link to the original post. https://medium.com/@papaponmx/looping-over-object-properties-with-ngfor-in-angular-869cd7b2ddcc
This is how to loop through a javascript object and put the data into a table.
<body>
<script>
function createTable(objectArray, fields, fieldTitles) {
let body = document.getElementsByTagName('body')[0];
let tbl = document.createElement('table');
let thead = document.createElement('thead');
let thr = document.createElement('tr');
for (p in objectArray[0]){
let th = document.createElement('th');
th.appendChild(document.createTextNode(p));
thr.appendChild(th);
}
thead.appendChild(thr);
tbl.appendChild(thead);
let tbdy = document.createElement('tbody');
let tr = document.createElement('tr');
objectArray.forEach((object) => {
let n = 0;
let tr = document.createElement('tr');
for (p in objectArray[0]){
var td = document.createElement('td');
td.appendChild(document.createTextNode(object[p]));
tr.appendChild(td);
n++;
};
tbdy.appendChild(tr);
});
tbl.appendChild(tbdy);
body.appendChild(tbl)
return tbl;
}
createTable([
{name: 'Banana', price: '3.04'}, // k[0]
{name: 'Orange', price: '2.56'}, // k[1]
{name: 'Apple', price: '1.45'}
])
</script>
There are a couple of options:
for..in for thatvar p = {
"p1": "value1",
"p2": "value2",
"p3": "value3"
};
for (const item in p) {
console.log(`key = ${item}, value = ${p[item]}`);
}
Object.entries() to create an array with all its enumerable properties. after that you can and loop through it using map, foreach or for..ofvar p = {
"p1": "value1",
"p2": "value2",
"p3": "value3"
};
Object.entries(p).map(item => {
console.log(item)
})
var p = {
"p1": "value1",
"p2": "value2",
"p3": "value3"
};
Object.entries(p).forEach(item => {
console.log(item)
})
var p = {
"p1": "value1",
"p2": "value2",
"p3": "value3"
};
for (const item of Object.entries(p)) {
console.log(item)
}
More about Object.entries()can be found here
You may use my library monadic-objects for that. It's designed to simplify object modificatons and make it behave like arrays:
p.forEach((key, value) => console.log(key, value))
Installation:
npm i monadic-objects
This library also includes methods:
mapfiltereverysomeSee README for more information!
An object becomes an iterator when it implements the .next() method
const james = {
name: 'James',
height: `5'10"`,
weight: 185,
[Symbol.iterator]() {
let properties = []
for (let key of Object.keys(james)) {
properties.push(key);
}
index = 0;
return {
next: () => {
let key = properties[index];
let value = this[key];
let done = index >= properties.length - 1;
index++;
return {
key,
value,
done
};
}
};
}
};
const iterator = james[Symbol.iterator]();
console.log(iterator.next().value); // 'James'
console.log(iterator.next().value); // `5'10`
console.log(iterator.next().value); // 185
If you want to iterate only over properties use one of the answers above, however if you want to iterate over everything including functions, then you might want to use Object.getOwnPropertyNames(obj)
for (let o of Object.getOwnPropertyNames(Math)) {
console.log(o);
}
I sometimes use this to fast test all functions on objects with simple inputs and outputs.
var p = {
"p1": "value1",
"p2": "value2",
"p3": "value3"
};
var myMap = new Map( Object.entries(p) );
for ( let [k, v] of myMap.entries() ) {
console.log( `${k}: ${v}` )
}
<h3>ECMAScript 2017</h3>
<p><b>Object.entries()</b> makes it simple to convert <b>Object to Map</b>:</p>
The nearest solution, close to python's enumerate function:
for key, value in enumerate(object):
# Do something
is a combo of Object.entries() and for-of loop:
for(let [key, value] of Object.entries(object)) {
// Do something
}
let object = {
key1: "value1",
key2: "value2",
key3: "value3",
key4: "value4",
key5: "value5"
};
for(let [key, value] of Object.entries(object)) {
console.log(`${key} -> ${value}`);
}