javascriptarraysajax

Issue calling $el with forEach() function in JavaScript


I am unable to use the element value inside the forEach() function

var filtered = rawData.map(function(x){
        return {
          state       : x.state,
          active      : x.active,
          deaths      : x.deaths,
          recovered   : x.recovered
        };
})

Using the above in the following loop :

for(i=1; i<=filtered.length; i++){
        let tr = document.createElement("tr");
        tr.setAttribute("align","center");    
        document.querySelector('tbody').appendChild(tr);

        ndata = ['state', 'active', 'deaths', 'recovered']
        ndata.forEach((el, k) => {
          let td$k = document.createElement('td');
          td$k.innerText = filtered[i].$el;        // <-- ERROR //
          tr.appendChild(td$k);
        }); 

The browser is throwing back this error:

app.js:201 Uncaught TypeError: Cannot read property '$el' of undefined


Solution

  • We can access an object's properties by using the dot notation or the bracket notation like:

    object.property
    object['property']
    

    But here el is a not a property on object filtered[i]. It is the key value as a string, so we need to use the bracket notation like:

    td$k.innerText = filtered[i][el];
    

    For more info check docs on Property Accessors.