In demand

ad1

Wednesday, September 16, 2015

JavaScript: Looping through Objects

Most API deliver responses in the form of objects and arrays of objects in jSON/JSONP format. Many times useful the data must be iterated over. The following three code snippets are for looping through objects. Though the output is the same there are differences in syntax.

The performance characteristics of the options  can be tested at  jsperf.com.  jsPerf provides an easy way to create and share test cases, comparing the performance of different JavaScript snippets by running benchmarks.




Data object:


var p =
    {
        "p1": "value1",
        "p2": "value2",
        "p3": "value3"
    };

1.

var keys = Object.keys(p),
    len = keys.length,
    i = 0,
    prop,
    value;
while (i < len) {
    prop = keys[i];
    value = p[prop];
    i += 1;
}

2.

for (var key in p) 
{
    if (p.hasOwnProperty(key))
    {
        console.log(key + " = " + p[key]);
    }
}

3.

keys = Object.keys(p);   // ["p1", "p2", "p3"]

for(i = 0; i < keys.length; i++)

{
    console.log(keys[i] + " = " + p[keys[i]]);   // p1=value1, p2=value2, p3=value3
}

Output:

p1 = values1
p2 = values2
p3 = values3

 

jsperf tests

 

Today's Links

Post a Comment

Print this!