Is There a Built-In Way to Loop Through the Properties of an Object

Is there a built-in way to loop through the properties of an object?

Built-in support since Handlebars 1.0rc1

Support for this functionality has been added to Handlebars.js, so there is no more need for external helpers.

How to use it

For arrays:

{{#each myArray}}
Index: {{@index}} Value = {{this}}
{{/each}}

For objects:

{{#each myObject}}
Key: {{@key}} Value = {{this}}
{{/each}}

Note that only properties passing the hasOwnProperty test will be enumerated.

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

What's the fastest way to iterate over an object's properties in Javascript?

1) There are many different ways to enumerate properties:

  • for..in (iterates over enumerable properties of the object and its prototype chain)
  • Object.keys(obj) returns the array of the enumerable properties, found directly on the object (not in its prototype chain)
  • Object.getOwnPropertyNames(obj) returns an array of all properties (enumerable or not) found directly on the object.
  • If you're dealing with multiple objects of the same "shape" (set of properties), it might make sense to "pre-compile" the iteration code (see the other answer here).
  • for..of can't be used to iterate an arbitrary object, but can be used with a Map or a Set, which are both suitable replacements for ordinary Objects for certain use-cases.
  • ...

Perhaps if you stated your original problem, someone could suggest a way to optimize.

2) I find it hard to believe that the actual enumeration is taking more than whatever you do with the properties in the loop body.

3) You didn't specify what platform you're developing for. The answer would probably depend on it, and the available language features depend on it too. E.g. in SpiderMonkey (Firefox JS interpreter) circa 2009 you could use for each(var x in arr) (docs) if you actually needed the values, not the keys. It was faster than for (var i in arr) { var x = arr[i]; ... }.

V8 at some point regressed the performance of for..in and subsequently fixed it. Here's a post on the internals of for..in in V8 in 2017: https://v8project.blogspot.com/2017/03/fast-for-in-in-v8.html

4) You probably just didn't include it in your snippet, but a faster way to do a for..in iteration is to make sure the variables you use in the loop are declared inside the function containing the loop, i.e.:

//slower
for (property in object) { /* do stuff */ }

//faster
for (var property in object) { /* do stuff */ }

5) Related to (4): while trying to optimize a Firefox extension I once noticed that extracting a tight loop into a separate function improved its performance (link). (Obviously, it doesn't mean you should always do that!)

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

Is there a good way to iterate over all the subproperties of a Javascript object?

You can use a recursive function like this:

var x = {
foo: 17,
bar: {
a: 2,
b: 7
}
}

function parseObject(something) {
var keys = Object.keys(something);
for (var i = 0; i < keys.length; i++) {
if (typeof something[keys[i]] === 'object') parseObject(something[keys[i]])
else console.log(keys[i] + " : " + something[keys[i]]);
}
}
parseObject(x);

Which generates the output:

foo : 17 
a : 2
b : 7

A note on this function. It recurses over anything that is an object. For instance, if you had an array in the object, you would get separate lines for each item in the array.

So for the following object:

var x = {
foo: 17,
bar: {
a: 2,
b: 7
},
foobar: [1,2,3]
}

The output would appear:

foo : 17 
a : 2
b : 7
0 : 1
1 : 2
2 : 3

There are obviously ways to handle this, but you will need to tailor the function to meet your requirements.

How to loop through an array containing objects and access their properties

Use forEach its a built-in array function. Array.forEach():

yourArray.forEach(function (arrayItem) {
var x = arrayItem.prop1 + 2;
console.log(x);
});

Looping through an object's (class instance) properties in python and printing them

Try not using private __dict__,
you have python built-in function called vars()

def print_properties(self):
for prop, value in vars(self).items():
print(prop, ":", value) # or use format

Explantion of vars, from pythom offical docs:

Return the __dict__ attribute for a module, class, instance, or any
other object with a __dict__ attribute.

Objects such as modules and instances have an updateable __dict__
attribute; however, other objects may have write restrictions on their
__dict__ attributes (for example, new-style classes use a dictproxy to prevent direct dictionary updates).

Without an argument, vars() acts like locals(). Note, the locals
dictionary is only useful for reads since updates to the locals
dictionary are ignored.



Related Topics



Leave a reply



Submit