我有以下数组:
[
{
"OrderID": 1,
"OrderDetails": [
{
"OrderDetailID": 7,
"ProductCode": "E456",
"Quantity": 1,
},
{
"OrderDetailID": 8,
"ProductCode": "E888",
"Quantity": 2
}
],
"OrderDate": "8/1/2018"
},
{
"OrderID": 2,
"OrderDetails": [
{
"OrderDetailID": 9,
"ProductCode": "N522",
"Quantity": 3
}
],
"OrderDate": "10/1/2018"
}
]
使用JavaScript,我需要将所有productCodes
连接到一个字符串中,以便结果应如下所示:
E456;E888;N522
我尝试使用map函数来获取OrderDetails
,并且能够这样做。但是当我再次像下面那样链接map函数时,details变量总是返回undefined
,所以我什至不能调用join函数来进行串联:
var details = this.orderData.map(function(i) {
return {
detail: i.OrderDetails
}}).map(function(j) {
return {
x: j.detail.ProductCode
}});
答案 0 :(得分:1)
使用.reduce
代替.map
,将每个ProductCode
推入累加器数组,然后通过;
加入:
const input = [{
"OrderID": 1,
"OrderDetails": [{
"OrderDetailID": 7,
"ProductCode": "E456",
"Quantity": 1,
},
{
"OrderDetailID": 8,
"ProductCode": "E888",
"Quantity": 2
}
],
"OrderDate": "8/1/2018"
},
{
"OrderID": 2,
"OrderDetails": [{
"OrderDetailID": 9,
"ProductCode": "N522",
"Quantity": 3
}],
"OrderDate": "10/1/2018"
}
];
const productCodes = input.reduce((a, { OrderDetails }) => {
a.push(...OrderDetails.map(({ ProductCode }) => ProductCode));
return a;
}, []);
console.log(productCodes.join(';'));
或者,在较新的浏览器上或使用polyfill,您可以使用flatMap
进一步降低它:
const productCodes = input.flatMap(
({ OrderDetails }) => OrderDetails.map(
({ ProductCode }) => ProductCode
)
);
const input = [{
"OrderID": 1,
"OrderDetails": [{
"OrderDetailID": 7,
"ProductCode": "E456",
"Quantity": 1,
},
{
"OrderDetailID": 8,
"ProductCode": "E888",
"Quantity": 2
}
],
"OrderDate": "8/1/2018"
},
{
"OrderID": 2,
"OrderDetails": [{
"OrderDetailID": 9,
"ProductCode": "N522",
"Quantity": 3
}],
"OrderDate": "10/1/2018"
}
];
const productCodes = input.flatMap(
({ OrderDetails }) => OrderDetails.map(
({ ProductCode }) => ProductCode
)
);
console.log(productCodes.join(';'));
答案 1 :(得分:0)
const arr=[{OrderID:1,OrderDetails:[{OrderDetailID:7,ProductCode:"E456",Quantity:1},{OrderDetailID:8,ProductCode:"E888",Quantity:2}],OrderDate:"8/1/2018"},{OrderID:2,OrderDetails:[{OrderDetailID:9,ProductCode:"N522",Quantity:3}],OrderDate:"10/1/2018"}];
const resp = arr.map(x => x.OrderDetails.map(y => y.ProductCode).join(';')).join(';');
console.log(resp)