首页 > 解决方案 > 无法在 TypeScript 中执行连接

问题描述

我有一个对象数组,如下所示

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

我想要逗号分隔的字符串中的名称值。

我使用下面的代码来实现这一点:

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

但我收到以下错误:

Uncaught (in promise) TypeError: Array.prototype.map 在 null 或 undefined 上调用

我也试过这个:

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

为此,我收到以下错误:

无法读取未定义的属性“地图”

标签: arraysreactjstypescriptjavascript-objectsreact-typescript

解决方案


tempObj本身就是一个数组。如果您只想处理它的第一个元素,那么您必须使用tempObj[0]然后执行以下操作

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);
});


推荐阅读