我有两个JSON对象:我需要用分支JSON中的属性值替换产品JSON中的属性值。
这是关于纯JavaScript的。
我已经尝试过使用map和filter进行测试,但是问题是,当某个产品没有品牌时,应用程序崩溃了,应该避免这种情况。我也用map尝试过,如果可以看到下面的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
});
因此,结果应该是产品中的brandDescr应该用来自品牌的描述替换,并且当品牌中没有匹配的描述时,应用程序也不会崩溃。
由于性能是一个问题,因此应避免执行双重过滤:第一次检查数组是否不为空,因此要检查产品是否有branchDescr,第二次检查实际替换。
我在以下位置创建了一个JSFiddle https://jsfiddle.net/Ben197/wpcz21e7/88/
答案 0 :(得分:1)
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
},
]
}
product.products.forEach(productItem => {
const maybeBrand = brand.brands.find(i => i.ID === productItem.brandID);
if (maybeBrand) {
productItem.brandDescr = maybeBrand.Description;
}
});
console.log(product.products);
答案 1 :(得分:1)
您可以使用filter()代替find(),而不是获取第一个元素(即... [0] .Description),而可以使用另一种方法来保存值:>
product.products.forEach(function(ele, idx) {
var descr = brand.brands.find((currele) => currele.ID == ele.brandID);
// if descr is not undefined use descr.Description else use the default...
ele.brandDescr = descr && descr.Description || ele.brandDescr;
});
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
},
]
}
product.products.forEach(function(ele, idx) {
var descr = brand.brands.find((currele) => currele.ID == ele.brandID);
ele.brandDescr = descr && descr.Description || ele.brandDescr;
});
console.log(product);
答案 2 :(得分:1)
这是一个简单的代码段。这将如您所愿。
{