【发布时间】:2017-10-06 12:19:36
【问题描述】:
我正在尝试在 react 中构建一个系统,这将使我能够从 JSON 文件中呈现产品列表,并(基于 JSON 中的信息)比较不同的数组并根据哪个数组分配最小产品数量产品包含在不同的包中(在 JSON 中称为“捆绑包”)。用户将能够选择一个捆绑包并查看包含哪些产品,这需要是动态的,因为 JSON 可能会随着时间而变化。
JSON信息如下:
{
"data": {
"adverts": [],
"bundles": [{
"id": "1",
"name": "Bronze Bundle",
"price": {
"installation": "99.99",
"recurring": "23.99"
},
"products": ["1", "2", "3", "4", "9", "10", "15", "15"]
}, {
"id": "2",
"name": "Silver Bundle",
"price": {
"installation": "99.99",
"recurring": "23.99"
},
"products": ["1", "2", "2", "2", "2", "4", "9", "10", "15", "15"]
}, {
"id": "3",
"name": "Gold Bundle",
"price": {
"installation": "99.99",
"recurring": "25.99"
},
"products": ["1", "2", "4", "5", "9", "10", "15", "15"]
}, {
"id": "4",
"name": "Build Your Own Bundle",
"price": {
"installation": "49.99",
"recurring": "9.99"
},
"products": ["1", "10"]
}],
"products": [{
"id": "1",
"name": "Product 1",
"price": {
"upfront": null,
"installation": "0.00",
"recurring": "0.00"
}
}, {
"id": "3",
"name": "Product 3",
"price": {
"upfront": "132.00",
"installation": "9.60",
"recurring": "2.75"
}
}, {
"id": "4",
"name": "Product 4",
"price": {
"upfront": "60.00",
"installation": "9.60",
"recurring": "1.25"
}
}, {
"id": "2",
"name": "Product 2",
"price": {
"upfront": "60.00",
"installation": "9.60",
"recurring": "1.25"
}
},{
"id": "5",
"name": "Product 5",
"price": {
"upfront": "228.00",
"installation": "9.60",
"recurring": "4.75"
}
}, {
"id": "6",
"name": "Product 6",
"price": {
"upfront": "96.00",
"installation": "9.60",
"recurring": "2.00"
}
}]
}
}
基本上我想要做的是将“Bundle”数组与“Products”数组进行比较,并根据包含的产品数量为产品分配一个最小值。
我将 Json 导入到 react 中使用:
import productdata from "./catalog.json";
我已将“捆绑包”中的信息传递到两个数组中,一个显示包含的产品列表,第二个显示产品数量。代码如下:
function foo(arr) {
var a = [], b = [], prev;
arr.sort();
for ( var i = 0; i < arr.length; i++ ) {
if ( arr[i] !== prev ) {
a.push(arr[i]);
b.push(1);
} else {
b[b.length-1]++;
}
prev = arr[i];
}
return {pincluded: [a],
qincluded: [b]
};
}
以及我用于尝试比较数组并将最小值分配给相关产品的当前代码(这发生在单独的反应组件中,因此它们已使用道具 pincluded = passProducts 和 qincluded = 传递数量):
var result = [];
var productList = productdata.data.products;
for (var j = 0; j < productList.length; j++){
var productList = this.props.passedProducts;
if (this.props.passedProducts == undefined){
productList = [];
}
var sortproducts = 0;
for (var i = 0; i < productList.length; i++) {
if (this.props.passedProducts[i] == 2){
sortproducts = this.props.passedQuantity;
}
}
result = [productdata.data.products][j], [sortproducts];
console.log(result)
}
我可以在控制台日志中呈现产品列表,但我需要能够在 react 中查看它并根据捆绑包中包含的数量分别为每行产品分配一些产品。
如果有人能就此提供一些建议,我将不胜感激。
【问题讨论】:
标签: arrays json reactjs for-loop if-statement