arrays - 无法在 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(",");
为此,我收到以下错误:
无法读取未定义的属性“地图”
解决方案
你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);
});
推荐阅读
- c++ - c4-pedestrian-detector.cpp:283:8:错误:“Show_Detection_Steps”未在此范围内声明
- javascript - await 在语句语法说明中的位置
- python - 我的 Python/Cython 迭代基准测试是否具有代表性?
- java - Java 泛型中的自动装箱和类型检测
- mongodb - 在尝试运行配置服务器的副本集时获取“副本集 ID 不匹配,我们的:<>,远程节点的:<>”
- python-3.x - 如何使用 input() 并将元素与数据库匹配
- ios - Alamofire 请求未发送 post 参数
- sql - 如何在字段名 vba excel SQL 中使用空格和点?
- javascript - MediaRecorder API 录制器在录制多个音轨时不会调用 onstop
- swift - 从一个视图转到另一个视图时的 CALayerInvalidGeometry