How to iterate over a JavaScript object?

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

I have an object in JavaScript:

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

I

相关标签:
18条回答
  • 2020-11-21 23:05

    ->if we iterate over a JavaScript object using and find key of array of objects

    Object.keys(Array).forEach(key => {
    
     console.log('key',key)
    
    })
    
    0 讨论(0)
  • 2020-11-21 23:06

    Using Object.entries you do something like this.

     // array like object with random key ordering
     const anObj = { 100: 'a', 2: 'b', 7: 'c' };
     console.log(Object.entries(anObj)); // [ ['2', 'b'],['7', 'c'],['100', 'a'] ]
    

    The Object.entries() method returns an array of a given object's own enumerable property [key, value]

    So you can iterate over the Object and have key and value for each of the object and get something like this.

    const anObj = { 100: 'a', 2: 'b', 7: 'c' };
    Object.entries(anObj).map(obj => {
       const key   = obj[0];
       const value = obj[1];
    
       // do whatever you want with those values.
    });
    

    or like this

    // Or, using array extras
    Object.entries(obj).forEach(([key, value]) => {
      console.log(`${key} ${value}`); // "a 5", "b 7", "c 9"
    });
    

    For a reference have a look at the MDN docs for Object Entries

    0 讨论(0)
  • 2020-11-21 23:07

    You can try using lodash- A modern JavaScript utility library delivering modularity, performance & extras js to fast object iterate:-

    var  users  =   {
        'fred':     { 
            'user':   'fred',
                'age':  40 
        },
        'pebbles':  { 
            'user':   'pebbles',
             'age':  1 
        }
    }; 
    _.mapValues(users,  function(o)  { 
        return  o.age; 
    });
    // => { 'fred': 40, 'pebbles': 1 } (iteration order is not guaranteed)
    // The `_.property` iteratee shorthand.
    console.log(_.mapValues(users,  'age')); // returns age property & value 
    console.log(_.mapValues(users,  'user')); // returns user property & value 
    console.log(_.mapValues(users)); // returns all objects 
    // => { 'fred': 40, 'pebbles': 1 } (iteration order is not guaranteed)
    <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash-compat/3.10.2/lodash.js"></script>

    0 讨论(0)
  • 2020-11-21 23:07
    var Dictionary = {
      If: {
        you: {
          can: '',
          make: ''
        },
        sense: ''
      },
      of: {
        the: {
          sentence: {
            it: '',
            worked: ''
          }
        }
      }
    };
    
    function Iterate(obj) {
      for (prop in obj) {
        if (obj.hasOwnProperty(prop) && isNaN(prop)) {
          console.log(prop + ': ' + obj[prop]);
          Iterate(obj[prop]);
        }
      }
    }
    Iterate(Dictionary);
    
    0 讨论(0)
  • 2020-11-21 23:07

    Here is a Hand Made Solution:

    function iterationForObject() {
        let base = 0,
            Keys= Object.keys(this);
        return {
            next: () => {
                return {
                    value: {
                        "key": Keys[base],
                        "value": this[Keys[base]]
                    },
                    done: !(base++ < Keys.length)
                };
            }
        };
    }
    Object.prototype[Symbol.iterator] = iterationForObject;
    

    And Then You Can Loop Any Object:

    for ( let keyAndValuePair of (Object Here) ) {
        console.log(`${keyAndValuePair.key} => ${keyAndValuePair.value}`);
    }
    
    0 讨论(0)
  • 2020-11-21 23:08

    With the new ES6/ES2015 features, you don't have to use an object anymore to iterate over a hash. You can use a Map. Javascript Maps keep keys in insertion order, meaning you can iterate over them without having to check the hasOwnProperty, which was always really a hack.

    Iterate over a map:

    var myMap = new Map();
    myMap.set(0, "zero");
    myMap.set(1, "one");
    for (var [key, value] of myMap) {
      console.log(key + " = " + value);
    }
    // Will show 2 logs; first with "0 = zero" and second with "1 = one"
    
    for (var key of myMap.keys()) {
      console.log(key);
    }
    // Will show 2 logs; first with "0" and second with "1"
    
    for (var value of myMap.values()) {
      console.log(value);
    }
    // Will show 2 logs; first with "zero" and second with "one"
    
    for (var [key, value] of myMap.entries()) {
      console.log(key + " = " + value);
    }
    // Will show 2 logs; first with "0 = zero" and second with "1 = one"
    

    or use forEach:

    myMap.forEach(function(value, key) {
      console.log(key + " = " + value);
    }, myMap)
    // Will show 2 logs; first with "0 = zero" and second with "1 = one"
    
    0 讨论(0)
提交回复
热议问题