-5

when i make data map i get error. where is the problem?

Error : UnhandledPromiseRejectionWarning: TypeError: betsModel.map is not a function

axios response ( String !):

var betsModel = {"13721":{"IdG":"1","N":"[] - 1","T":7,"A":true},"13722":{"IdG":"1","N":"[] - 2","T":7,"A":true},"6352":{"IdG":"1","N":"Zaman Sona Erdiğinde Beraberlik","T":1,"A":true}};

Parser

module.exports = (req, res) => {
    var uri = 'x';
    Axios({
        method: "GET",
        url: uri,
        timeout: 5000
    }).then(async response => {
        var e = response.data.match(/\= \{(.*?)\}\}\;/g);
        var betsModel = e[1].replace(/= /g,'');
        betsModel = JSON.parse(betsModel.replace(/}};/g,'}}'));
        betsModel.map(a => {
            console.log(a);
        });
    });
}
  • 2
    [`Array.prototype.map`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map) is an array method. `betsModel` is an object. There is no `Object.prototype.map`. Unrelated: don't use `map` without return value. Use `forEach` instead. – jabaa Sep 16 '21 at 23:47
  • @jabaa forEach is also an array method. It will not work for an object. – Don Rajitha Dissanayake Sep 17 '21 at 05:54
  • @DonRajithaDissanayake Yes, I know. That's the reason I wrote _"Unrelated"_ in front of it. But you should not use `map` to call a function for each element without return value. – jabaa Sep 17 '21 at 06:24

1 Answers1

0

Object iteration and array iterations are two different things. Here "betsModel" is an object. Hence map function will not work.

There are few ways to achieve what you do.

1. Object.values MDN Reference for Object.Values

Object.values(betsModel).map(value => {
         console.log(a);
    });

2. For In MDN Reference for , FOR IN

for (const prop in betsModel) {   
        if (betsModel.hasOwnProperty(prop)) {
             console.log(`obj.${prop} = ${obj[prop]}`);   
        } 
     }

Here is a similar question How to loop through a plain JavaScript object with the objects as members

  • Why would you create an array of `undefined` in your first snippet? `forEach` is much faster in that case. – jabaa Sep 17 '21 at 06:54