How to iterate over a JavaScript object?

后端 未结 18 1700
失恋的感觉
失恋的感觉 2020-11-21 22:52

I have an object in JavaScript:

{
    abc: \'...\',
    bca: \'...\',
    zzz: \'...\',
    xxx: \'...\',
    ccc: \'...\',
    // ...
}

I

18条回答
  •  时光说笑
    2020-11-21 23:10

    Really a PITA this is not part of standard Javascript.

    /**
     * Iterates the keys and values of an object.  Object.keys is used to extract the keys.
     * @param object The object to iterate
     * @param fn (value,key)=>{}
     */
    function objectForEach(object, fn) {
        Object.keys(object).forEach(key => {
            fn(object[key],key, object)
        })
    }
    

    Note: I switched the callback parameters to (value,key) and added a third object to make the API consistent other APIs.

    Use it like this

    const o = {a:1, b:true};
    objectForEach(o, (value, key, obj)=>{
        // do something
    });
    

提交回复
热议问题