Search code examples
arraysreactjstypescriptjavascript-objectsreact-typescript

Not able to perform join in TypeScript


I have an array of objects as shown below

var tempObj =  [{
"isAvailable": true,
"receipent": [{
    "id": "a6aedf0c34",
    "receipentName": "ABC"
}, {
    "id": "a6aedbc34",
    "receipentName": "XYZ"
}]  }]

And I want name value in a comma-separated string.

I used the below code to achieve this:

 var b = Array.prototype.map.call(tempObj.receipent, function (item) {
          return item.receipentName;
        }).join(",");

But I am getting the below error:

Uncaught (in promise) TypeError: Array.prototype.map called on null or undefined

I also tried this:

  var to = tempObj.receipent;
   var b = to.map(e => e.receipentName).join(",");

For this I am getting the below error:

Cannot read property 'map' of undefined


Solution

  • Your tempObj is itself an array. If you just want to process its first element then you have to use tempObj[0] and then do as follows

    var tempObj =  [{
    "isAvailable": true,
    "receipent": [{
        "id": "a6aedf0c34",
        "receipentName": "ABC"
    }, {
        "id": "a6aedbc34",
        "receipentName": "XYZ"
    }]  }];
    
    //tempObj = JSON.parse(tempObj);
    var b = tempObj[0].receipent.map(o => o.receipentName).join(",");
    
    console.log(b);
    
    // In case you want to do it for every tempObj then do as follows
    tempObj.forEach(obj => {
      const _b = obj.receipent.map(o => o.receipentName).join(",");
      console.log(_b);
    });