【发布时间】:2019-08-21 18:02:26
【问题描述】:
我有两个 JSON 对象:我需要将产品 JSON 中的属性值替换为分支 JSON 中的属性值。
这是关于纯 JavaScript 的。
我已经尝试过使用地图和过滤器,但问题是当某个产品没有品牌时,应用程序会崩溃,应该防止这种情况发生。我也用地图尝试过,如果看到下面的 JSFiddle 链接。
var product = {
products: [{
ID: 1,
brandDescr: 'substitute', //this value should be substituded with the branch Description
brandID: 1,
colorCode: 2,
colorDesc: 'substitute',
},
{
ID: 2,
brandDescr: 'substitute',
brandID: 2,
colorCode: 3,
colorDesc: 'substitute',
},
{
ID: 3,
brandDescr: 'substitute',
brandID: 12,
colorCode: 3,
colorDesc: 'substitute',
}
]
}
var brand = {
brands: [{
Description: 'BMW',
ID: 1
},
{
Description: 'Mercedes',
ID: 2
},
{
Description: 'Audi',
ID: 3
},
]
}
/**mthis method crashes when there is no Description for a Brand.
*for example for product ID 3 there is no brand description because brandID
* 12 does not exist
*/
product.products.forEach((x) => {
x.brandDescr = brand.brands.filter(function (y) {
console.log('Value: ' + x.brandID + y.ID)
return x.brandID == y.ID
})[0].Description
});
因此结果应该是 product 中的 brandDescr 应替换为来自品牌的描述,并且当品牌中没有匹配的描述时,应用程序不应崩溃。
并且因为性能是一个问题,所以应该防止做双重过滤:第一次检查数组是否不为空,所以检查是否有一个产品的branchDescr可用,第二次做实际替换。
【问题讨论】:
标签: javascript arrays mapping filtering