How to Iterate (Keys, Values) in JavaScript

How to iterate (keys, values) in JavaScript?

tl;dr

  1. In ECMAScript 2017, just call Object.entries(yourObj).
  2. In ECMAScript 2015, it is possible with Maps.
  3. In ECMAScript 5, it is not possible.

ECMAScript 2017

ECMAScript 2017 introduced a new Object.entries function. You can use this to iterate the object as you wanted.

'use strict';

const object = {'a': 1, 'b': 2, 'c' : 3};

for (const [key, value] of Object.entries(object)) {
console.log(key, value);
}

Output

a 1
b 2
c 3


ECMAScript 2015

In ECMAScript 2015, there is not Object.entries but you can use Map objects instead and iterate over them with Map.prototype.entries. Quoting the example from that page,

var myMap = new Map();
myMap.set("0", "foo");
myMap.set(1, "bar");
myMap.set({}, "baz");

var mapIter = myMap.entries();

console.log(mapIter.next().value); // ["0", "foo"]
console.log(mapIter.next().value); // [1, "bar"]
console.log(mapIter.next().value); // [Object, "baz"]

Or iterate with for..of, like this

'use strict';

var myMap = new Map();
myMap.set("0", "foo");
myMap.set(1, "bar");
myMap.set({}, "baz");

for (const entry of myMap.entries()) {
console.log(entry);
}

Output

[ '0', 'foo' ]
[ 1, 'bar' ]
[ {}, 'baz' ]

Or

for (const [key, value] of myMap.entries()) {
console.log(key, value);
}

Output

0 foo
1 bar
{} baz


ECMAScript 5:

No, it's not possible with objects.

You should either iterate with for..in, or Object.keys, like this

for (var key in dictionary) {
// check if the property/key is defined in the object itself, not in parent
if (dictionary.hasOwnProperty(key)) {
console.log(key, dictionary[key]);
}
}

Note: The if condition above is necessary only if you want to iterate over the properties which are the dictionary object's very own. Because for..in will iterate through all the inherited enumerable properties.

Or

Object.keys(dictionary).forEach(function(key) {
console.log(key, dictionary[key]);
});

How do I loop through or enumerate a JavaScript object?

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

How to loop through key/value object in Javascript?

Beware of properties inherited from the object's prototype (which could happen if you're including any libraries on your page, such as older versions of Prototype). You can check for this by using the object's hasOwnProperty() method. This is generally a good idea when using for...in loops:

var user = {};

function setUsers(data) {
for (var k in data) {
if (data.hasOwnProperty(k)) {
user[k] = data[k];
}
}
}

JavaScript iterate key & value from json?

Use Object.keys() to get keys array and use forEach() to iterate over them.

var data = {
"VERSION": "2006-10-27.a",
"JOBNAME": "EXEC_",
"JOBHOST": "Test",
"LSFQUEUE": "45",
"LSFLIMIT": "2006-10-27",
"NEWUSER": "3",
"NEWGROUP": "2",
"NEWMODUS": "640"
};

Object.keys(data).forEach(function(key) {
console.log('Key : ' + key + ', Value : ' + data[key])
})

For..In loops in JavaScript - key value pairs

If you can use ES6 natively or with Babel (js compiler) then you could do the following:

const test = {a: 1, b: 2, c: 3};

for (const [key, value] of Object.entries(test)) {
console.log(key, value);
}

Iterate over objects and return key-value pairs from an array in Javascript

Okay, So after spending some time on basics I realized it was quite straightforward.

Learnings:

  1. Move the incoming backend response out from consumeAPI()
  2. Pop-out values of each object from it.
  3. Return the Object to calculatePlot() function.

So now the consumeAPI() looks like this.

     function consumeAPI() {
const value = sample_graphs.pop();

const x_1 = value.quadrant1_x;
const y_1 = value.quadrant1_y;
const x_2 = value.quadrant2_x;
const y_2 = value.quadrant2_y;
const x_3 = value.quadrant3_x;
const y_3 = value.quadrant3_y;
const x_4 = value.quadrant4_x;
const y_4 = value.quadrant4_y;

let retObj = {
x1: x_1 * range,
y1: y_1 * range,
x2: x_2 * range,
y2: y_2 * range,
x3: x_3 * range,
y3: y_3 * range,
x4: x_4 * range,
y4: y_4 * range,
};

return retObj;

}

Rest remains the same.

 function generateRandomUser() {
const user = consumeAPI();
return calculatePlot(user);
}
let sample_graph = [
{
quadrant1_x: "0.17",
quadrant2_x: "0.53",
quadrant3_x: "-0.48",
quadrant4_x: "-0.86",
quadrant1_y: "0.31",
quadrant2_y: "-0.21",
quadrant3_y: "-0.60",
quadrant4_y: "0.50",
},
...

];

// consumeAPI() goes here

for (let i = 0; i < maxUsers; i++) {
let plot = generateRandomUser();
addUser(plot);
calculateMidPoint(plot);
}

Sample: JSFiddle

How to iterate over a JavaScript object?

For iterating on keys of Arrays, Strings, or Objects, use for .. in :

for (let key in yourobject) {
console.log(key, yourobject[key]);
}

With ES6, if you need both keys and values simultaneously, do

for (let [key, value] of Object.entries(yourobject)) {
console.log(key, value);
}

To avoid logging inherited properties, check with hasOwnProperty :

for (let key in yourobject) {
if (yourobject.hasOwnProperty(key)) {
console.log(key, yourobject[key]);
}
}

You don't need to check hasOwnProperty when iterating on keys if you're using a simple object (for example one you made yourself with {}).

This MDN documentation explains more generally how to deal with objects and their properties.

If you want to do it "in chunks", the best is to extract the keys in an array. As the order isn't guaranteed, this is the proper way. In modern browsers, you can use

let keys = Object.keys(yourobject);

To be more compatible, you'd better do this :

 let keys = [];
for (let key in yourobject) {
if (yourobject.hasOwnProperty(key)) keys.push(key);
}

Then you can iterate on your properties by index: yourobject[keys[i]] :

for (let i=300; i < keys.length && i < 600; i++) { 
console.log(keys[i], yourobject[keys[i]]);
}


Related Topics



Leave a reply



Submit