我有此数据:
let myInputArray = [
{
"id": 1,
"commercialRanges": [
{
"rangeId": "305",
"rangeName": "FIXE"
},
{
"rangeId": "306",
"rangeName": "POSTPAID"
},
],
"active": true,
"pefName": "Alertes",
"roles": "ADVISOR",
"equipmentTypes": "PC",
},
...
{
"id": 1523,
"commercialRanges": [
{
"rangeId": "700",
"rangeName": "POSTPAID"
},
{
"rangeId": "500",
"rangeName": "PREPAID"
},
]
,
"active": true,
"pefName": "Alertes",
"roles": "ADVISOR",
"equipmentTypes": "PC",
},
]
我想更新我的数据: 从其格式(对象数组)转换属性“ commercialRanges” ->转换为简单的字符串:(其中连接了不同的“ rangeName ”值)
我得到的数组将是这样的:
myResultArray = [
{
"id": 1,
"commercialRanges": "FIXE,POSTPAID",
"active": true,
"pefName": "Alertes",
"roles": "ADVISOR",
"equipmentTypes": "PC",
},
...
{
"id": 1523,
"commercialRanges": "POSTPAID,PREPAID",
"active": true,
"pefName": "Alertes",
"roles": "ADVISOR",
"equipmentTypes": "PC",
},
]
因此,我应该转换嵌入对象“ commercialRanges”
"commercialRanges": [
{
"rangeId": "305",
"rangeName": "FIXE"
},
{
"rangeId": "306",
"rangeName": "POSTPAID"
},
]
至:
"commercialRanges": "FIXE,POSTPAID"
答案 0 :(得分:0)
您可以尝试使用Array.forEach,Array.map和Array.join
let myInputArray = [{"id":1,"commercialRanges":[{"rangeId":"305","rangeName":"FIXE"},{"rangeId":"306","rangeName":"POSTPAID"}],"active":true,"pefName":"Alertes","roles":"ADVISOR","equipmentTypes":"PC"}];
myInputArray.forEach(o => o.commercialRanges = o.commercialRanges.map(r => r.rangeName).join(','));
console.log(myInputArray);
答案 1 :(得分:0)
基本思想是循环遍历myInputArray
数组并将commercialRanges
简化为字符串;为此,您还需要使用循环。
我建议您在Array.prototype.reduce
上使用myInputArray
方法,然后在Array.prototype.map
数组上使用commercialRanges
,因为这是最简单/最优雅的实现方式这个。您也可以将map
和reduce
用于两个循环。完全由您决定。这是我的去
let myInputArray = [
{
"id": 1,
"commercialRanges": [
{
"rangeId": "305",
"rangeName": "FIXE"
},
{
"rangeId": "306",
"rangeName": "POSTPAID"
},
],
"active": true,
"pefName": "Alertes",
"roles": "ADVISOR",
"equipmentTypes": "PC",
},
...
{
"id": 1523,
"commercialRanges": [
{
"rangeId": "700",
"rangeName": "POSTPAID"
},
{
"rangeId": "500",
"rangeName": "PREPAID"
},
]
,
"active": true,
"pefName": "Alertes",
"roles": "ADVISOR",
"equipmentTypes": "PC",
},
]
const myInputString = myInputArray.reduce((arr, obj) => [
...arr,
{
...obj,
commercialRanges: obj.commercialRanges.map(rObj => rObj.rangeName).join(',')
}
], [])
选项2:
用Array.prototype.map
const myInputString = myInputArray.map(obj => ({
...obj,
commercialRanges: obj.commercialRanges.map(rObj => rObj.rangeName).join(',')
})
)