Why is “forEach not a function” for this object?

后端 未结 3 1580
梦毁少年i
梦毁少年i 2020-12-13 05:58

This is probably something really dumb, but I don\'t understand why this doesn\'t work.

var a = {\"cat\":\"large\"};

a.forEach(function(value, key, map){
           


        
相关标签:
3条回答
  • 2020-12-13 06:32

    Object does not have forEach, it belongs to Array prototype. If you want to iterate through each key-value pair in the object and take the values. You can do this:

    Object.keys(a).forEach(function (key){
        console.log(a[key]);
    });
    

    Usage note: For an object v = {"cat":"large", "dog": "small", "bird": "tiny"};, Object.keys(v) gives you an array of the keys so you get ["cat","dog","bird"]

    0 讨论(0)
  • 2020-12-13 06:34

    When I tried to access the result from

    Object.keys(a).forEach(function (key){ console.log(a[key]); });

    it was plain text result with no key-value pairs Here is an example

    var fruits = {
        apple: "fruits/apple.png",
        banana: "fruits/banana.png",
        watermelon: "watermelon.jpg",
        grapes: "grapes.png",
        orange: "orange.jpg"
    }
    

    Now i want to get all links in a separated array , but with this code

        function linksOfPics(obJect){
    Object.keys(obJect).forEach(function(x){
        console.log('\"'+obJect[x]+'\"');
    });
    }
    

    the result of :

    linksOfPics(fruits)
    
    
    
    "fruits/apple.png"
     "fruits/banana.png"
     "watermelon.jpg"
     "grapes.png"
     "orange.jpg"
    undefined
    

    I figured out this one which solves what I'm looking for

      console.log(Object.values(fruits));
    ["fruits/apple.png", "fruits/banana.png", "watermelon.jpg", "grapes.png", "orange.jpg"]
    
    0 讨论(0)
  • 2020-12-13 06:43

    If you really need to use a secure foreach interface to iterate an object and make it reusable and clean with a npm module, then use this, https://www.npmjs.com/package/foreach-object

    Ex:

    import each from 'foreach-object';
       
    const object = {
       firstName: 'Arosha',
       lastName: 'Sum',
       country: 'Australia'
    };
       
    each(object, (value, key, object) => {
       console.log(key + ': ' + value);
    });
       
    // Console log output will be:
    //      firstName: Arosha
    //      lastName: Sum
    //      country: Australia
    
    0 讨论(0)
提交回复
热议问题