60

I want to traverse through JavaScript object's property

var obj =
{
 a: 'value1',
 b: 'value2',
 c: 'value3',
 d: 'value4'
};
for (var prop in obj) {
 prop = 'xxx';
}

But the above code is not working. Can you help me how to do so ?

NG_
7,2318 gold badges50 silver badges70 bronze badges
asked Dec 6, 2010 at 11:53

8 Answers 8

96

You should check that the property belongs to the object and not a prototype.

for (var prop in obj) {
 if (obj.hasOwnProperty(prop)) {
 obj[prop] = 'xxx';
 }
}
answered Dec 6, 2010 at 11:58

3 Comments

Why would I still want to check "hasOwnProperty"? What can go wrong with "prop in obj"?
Because it will also return inherited properties from the prototype chain. Hence you need to check if the property is from the current object. You can read further here: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
It has no inherited properties
85

prop will reference the property name, not its value.

for (var prop in obj) {
 obj[prop] = 'xxx';
}

Construct documentation.

Also you may want to check if the property belongs to the object using hasOwnProperty. It may happen that someone adds properties to the prototype and those are also iterated by for ... in.

answered Dec 6, 2010 at 11:54

Comments

27

Here is how it is done using the ES5 - Object.keys() :

Object.keys(obj).forEach(function(key, idx) {
 ...
}); 

http://jsfiddle.net/magiccrafter/bvwenh5d/

Mozilla's docs: link

answered Dec 3, 2015 at 21:16

2 Comments

I prefer this approach because it only iterates through an objects "own" properties...e.g. no need for the hasOwnProperty conditional. Hooray for modern JS!
Some ES6 arrow function to avoid "this" problems Object.keys(obj).forEach((key, idx) => { ... });
7

Using ecmascript2017: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/entries

const object1 = {
 a: 'somestring',
 b: 42
};
for (let [key, value] of Object.entries(object1)) {
 console.log(`${key}: ${value}`);
}
answered Oct 29, 2019 at 20:35

Comments

2
for(let i = 0; i < Object.entries(dog).length; i++){
 this.temp.push(Object.entries(dog)[i]);
}
answered Apr 27, 2018 at 23:52

Comments

2
const obj = {
"abc":1, "def":2
}
for (let key in obj){
 console.log(key+":"+obj[key])
}
answered Mar 15, 2020 at 7:48

Comments

1

(削除) If you're in an ES6 friendly environment, you can also try using the for...of loop which is closer to your original attempt. (削除ここまで)

EDIT: As Caleb pointed out, for..of is specific to collections with the Symbol.iterator property (e.g. not standard JS objects).

But I'm leaving this answer here in case anybody else finds it useful at some point to have it pointed out explicitly that a for..of is not a great solution here.

let obj = {};
for (let prop of obj) { // This will throw an error
 prop = 'xxx';
}

Reference: MDN - for...of

answered Sep 29, 2016 at 17:47

4 Comments

I think needs a little tweaking since obj is not an array. Also better to use let if you have an ES6 environment. for (let prop of Object.keys(obj)) { obj[prop] = 'xxx'; }
@Caleb The point of the 'for...of' loop is to iterate over an object, not an array. If you're going to fetch the keys, then you may as well just use a standard for loop but you're also making the code unnecessarily complex. +1 on using 'let' tho
I tried it in jsfiddle to double check but the for ... of can't iterate through an object. It responds with a Uncaught TypeError: obj[Symbol.iterator] is not a function error. But yeah it doesn't make it seem very useful if you have to write it what I have above in my comment...
@Caleb Yep, my mistake. for...of doesn't support standard js objects.
-1
var temp= {"6s","vikash","500"};
console.log([...temp]); //["6s","vikash","500"]
Cody Gray
246k53 gold badges508 silver badges590 bronze badges
answered Dec 23, 2020 at 9:14

1 Comment

Brevity is acceptable, but fuller explanations are better.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.