简体   繁体   English

遍历 Javascript 对象属性

[英]Traverse through Javascript object properties

I want to traverse through JavaScript object's property我想遍历 JavaScript 对象的属性

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?你能帮我怎么做吗?

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';
    }
}

prop will reference the property name, not its value. prop将引用属性名称,而不是它的值。

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 .您还可能想使用hasOwnProperty检查该属性是否属于该对象。 It may happen that someone adds properties to the prototype and those are also iterated by for... in .可能有人向原型添加了属性,并且这些属性也被for... in迭代。

Here is how it is done using the ES5 - Object.keys():这是使用 ES5 - Object.keys() 完成的方法:

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

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

Mozilla's docs: link Mozilla 的文档: 链接

Using ecmascript2017: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/entries使用 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}`);
}
for(let i = 0; i < Object.entries(dog).length; i++){
  this.temp.push(Object.entries(dog)[i]);
}
const obj = {
"abc":1, "def":2
}
for (let key in obj){
  console.log(key+":"+obj[key])
}

If you're in an ES6 friendly environment, you can also try using the for...of loop which is closer to your original attempt. 如果你在 ES6 友好的环境中,你也可以尝试使用更接近你最初尝试的 for...of 循环。

EDIT: As Caleb pointed out, for..of is specific to collections with the Symbol.iterator property (eg not standard JS objects).编辑:正如 Caleb 指出的那样, for..of特定于具有 Symbol.iterator 属性的集合(例如,不是标准的 JS 对象)。

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.但是我在这里留下这个答案,以防其他人发现在某些时候明确指出for..of在这里不是一个很好的解决方案是有用的。

let obj = {};

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

Reference: MDN - for...of参考: MDN - 为...的

var temp= {"6s","vikash","500"};
console.log([...temp]); //["6s","vikash","500"]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM