我有一个类似的数组,
var result = [
{
"sItem" : [
"Pizza Margherita","Pizza marinara"
],
"sImage" : [
"https://assets.marthastewart.com/styles/wmax-300/d31/pizza-margherita-0606-mla102155/pizza-margherita-0606-mla102155_vert.jpg","https://www.silviocicchi.com/pizzachef/wp-content/uploads/2015/02/m-evid-672x372.jpg"
],
"nQuantity" : 1,
"eDeliveryStatus" : "n",
"nPrice" : 215,
"sReceiptId" : "pRjZpGzIDPpX",
}
];
想使对象像,我正在通过标题数组推送数据的循环。
[
{
"title":"Pizza Margherita",
"subtitle":"Pizza Margherita",
"quantity":1,
"price":215,
"currency":"INR",
"image_url":"https://images.mcdelivery.co.in/hardcastle-restaurants-pvt-ltd/image/upload/q_auto:low,fl_lossy,w_300/v1484907263/Items/2754.png"
},
{
"title":"Pizza marinara",
"subtitle":"Pizza marinara",
"quantity":1,
"price":215,
"currency":"INR",
"image_url":"https://www.silviocicchi.com/pizzachef/wp-content/uploads/2015/02/m-evid-672x372.jpg"
}
]
这就是我正在尝试但失败的方式:(,
result.forEach(el => {
el.sItem.forEach(el2 => {
elementRec.push({
"title": el2,
"subtitle": el2,
"quantity": el.nQuantity,
"price": el.nPrice,
"currency": "INR",
"image_url": el.sImage
})
});
})
我知道这是错误的,但是对Javascript来说是新的。
答案 0 :(得分:2)
您快到了。
在您forEach
中,添加一个index
参数,并使用它从sImage
数组中检索正确的图像:
el.sItem.forEach((el2, index) => {
elementRec.push({
"title": el2,
"subtitle": el2,
"quantity": el.nQuantity,
"price": el.nPrice,
"currency": "INR",
"image_url": el.sImage[index]
})
});
var result = [
{
"sItem" : [
"Pizza Margherita",
"Pizza marinara"
],
"sImage" : [
"https://assets.marthastewart.com/styles/wmax-300/d31/pizza-margherita-0606-mla102155/pizza-margherita-0606-mla102155_vert.jpg",
"https://www.silviocicchi.com/pizzachef/wp-content/uploads/2015/02/m-evid-672x372.jpg"
],
"nQuantity" : 1,
"eDeliveryStatus" : "n",
"nPrice" : 215,
"sReceiptId" : "pRjZpGzIDPpX",
}
];
var elementRec = [];
result.forEach(el => {
el.sItem.forEach((el2, index) => {
elementRec.push({
"title": el2,
"subtitle": el2,
"quantity": el.nQuantity,
"price": el.nPrice,
"currency": "INR",
"image_url": el.sImage[index]
})
});
});
console.log(elementRec);
答案 1 :(得分:1)
您可以通过破坏和简短属性将内部sItem
和相应的sImage
映射到新对象。
var data = [{ sItem: ["Pizza Margherita", "Pizza marinara"], sImage: ["https://assets.marthastewart.com/styles/wmax-300/d31/pizza-margherita-0606-mla102155/pizza-margherita-0606-mla102155_vert.jpg", "https://www.silviocicchi.com/pizzachef/wp-content/uploads/2015/02/m-evid-672x372.jpg"], nQuantity: 1, eDeliveryStatus: "n", nPrice: 215, sReceiptId: "pRjZpGzIDPpX" }],
result = data.reduce((r, { sItem, sImage, nQuantity: quantity, nPrice: price }) =>
r.concat(sItem.map((title, i) => ({
title, subTitle: title, quantity, price, currency: 'INR', image_url: sImage[i]
}))),
[]
);
console.log(result);
答案 2 :(得分:-1)
我认为您正在尝试做这样的事情。首先创建一个新数组。我称它为converted
。然后像这样用result
将.forEach()
对象推入其中。
var converted = [];
result.forEach(function(i){
converted.push({
"title": i.sItem[0],
"subtitle": i.sItem[0],
"quantity": i.nQuantity,
"price": i.nPrice,
"currency": "INR",
"image_url": i.sImage[0]
});
})
尝试这个fiddle