简体   繁体   English

使用 Lodash 遍历 JavaScript 对象中的属性

[英]Loop through properties in JavaScript object with Lodash

Is it possible to loop through the properties in a JavaScript object?是否可以遍历 JavaScript 对象中的属性? For instance, I have a JavaScript object defined as this:例如,我有一个 JavaScript 对象定义如下:

myObject.options = {
  property1: 'value 1',
  property2: 'value 2'
};

Properties will get dynamically added to this object.属性将动态添加到此对象。 Is there a way for me to just loop through and do a check if a property exists?有没有办法让我循环并检查属性是否存在? If so, how?如果是这样,如何?

Use _.forOwn() .使用_.forOwn()

_.forOwn(obj, function(value, key) { } );

https://lodash.com/docs#forOwn https://lodash.com/docs#forOwn

Note that forOwn checks hasOwnProperty , as you usually need to do when looping over an object's properties.请注意, forOwn检查hasOwnProperty ,就像在循环对象的属性时通常需要做的那样。 forIn does not do this check. forIn不做这个检查。

Yes you can and lodash is not needed... ie是的,你可以,不需要 lodash ......即

for (var key in myObject.options) {
  // check also if property is not inherited from prototype
  if (myObject.options.hasOwnProperty(key)) { 
    var value = myObject.options[key];
  }
}

Edit : the accepted answer ( _.forOwn() ) should be https://stackoverflow.com/a/21311045/528262编辑:接受的答案( _.forOwn() )应该是https://stackoverflow.com/a/21311045/528262

对于您声明的“检查属性是否存在”的愿望,您可以直接使用 Lo-Dash 的has

var exists = _.has(myObject, propertyNameToCheck);

You can definitely do this with vanilla JS like stecb has shown, but I think each is the best answer to the core question concerning how to do it with lodash.你绝对可以像 stecb 展示的那样使用 vanilla JS 做到这一点,但我认为each都是关于如何使用 lodash 做到这一点的核心问题的最佳答案。

_.each( myObject.options, ( val, key ) => { 
    console.log( key, val ); 
} );

Like JohnnyHK mentioned, there is also the has method which would be helpful for the use case, but from what is originally stated set may be more useful.就像 JohnnyHK 提到的那样,还有has方法对用例很有帮助,但从最初声明的set可能更有用。 Let's say you wanted to add something to this object dynamically as you've mentioned:假设你想像你提到的那样动态地向这个对象添加一些东西:

let dynamicKey = 'someCrazyProperty';
let dynamicValue = 'someCrazyValue';

_.set( myObject.options, dynamicKey, dynamicValue );

That's how I'd do it, based on the original description.根据原始描述,我就是这样做的。

Lets take below object as example让我们以下面的对象为例

let obj = { property1: 'value 1', property2: 'value 2'};

First fetch all the key in the obj首先获取obj中的所有key

let keys = Object.keys(obj) //it will return array of keys

and then loop through it然后循环遍历它

keys.forEach(key => //your way)

just putting all together只是把所有东西放在一起

Object.keys(obj).forEach(key=>{/*code here*/})

In ES6, it is also possible to iterate over the values of an object using the for..of loop.在 ES6 中,还可以使用for..of循环迭代对象的值。 This doesn't work right out of the box for JavaScript objects, however, as you must define an @@iterator property on the object.但是,对于 JavaScript 对象,这不是开箱即用的,因为您必须在对象上定义 @@iterator 属性。 This works as follows:其工作原理如下:

  • The for..of loop asks the "object to be iterated over" (let's call it obj1 for an iterator object. The loop iterates over obj1 by successively calling the next() method on the provided iterator object and using the returned value as the value for each iteration of the loop. for..of循环询问“要迭代的对象”(对于迭代器对象,我们称其为 obj1。该循环通过连续调用提供的迭代器对象上的 next() 方法并使用返回值作为迭代器对象来迭代 obj1循环每次迭代的值。
  • The iterator object is obtained by invoking the function defined in the @@iterator property, or Symbol.iterator property, of obj1.迭代器对象是通过调用 obj1 的 @@iterator 属性或 Symbol.iterator 属性中定义的函数获得的。 This is the function you must define yourself, and it should return an iterator object这是你必须自己定义的函数,它应该返回一个迭代器对象

Here is an example:下面是一个例子:

const obj1 = {
  a: 5,
  b: "hello",
  [Symbol.iterator]: function() {
    const thisObj = this;
    let index = 0;
    return {
      next() {
        let keys = Object.keys(thisObj);
        return {
          value: thisObj[keys[index++]],
          done: (index > keys.length)
        };
      }
    };
  }
};

Now we can use the for..of loop:现在我们可以使用for..of循环:

for (val of obj1) {
  console.log(val);
}    // 5 hello

It would be helpful to understand why you need to do this with lodash.了解为什么需要使用 lodash 执行此操作会很有帮助。 If you just want to check if a key exists in an object, you don't need lodash.如果您只想检查对象中是否存在键,则不需要 lodash。

myObject.options.hasOwnProperty('property');

If your looking to see if a value exists, you can use _.invert如果您想查看值是否存在,您可以使用_.invert

_.invert(myObject.options)[value]

如果您只想循环映射属性值,请使用_.mapValues

If you are checking, if the property exists in the object as stated in the question asked, you can use lodash libray _.has method如果您正在检查,如果该属性存在于所问问题中所述的对象中,您可以使用 lodash libray _.has方法

_.has(object, path)

Let me give you an example, how to use it.让我给你举个例子,如何使用它。

consider an object考虑一个对象

    const user = {
    name : "prabhat",
    age: 27,
    height: "5.7"
   }

if you want to check, if name property exist in the object,you can use _.has method as follows如果要检查对象中是否存在name属性,可以使用_.has方法如下

_.has(user, 'name') //true
_.has(user, 'address') //false

you will get a boolean true/false in return.你会得到一个boolean真/假作为回报。

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

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