我有一个json对象,如下所示
[
{
"MerchantName": "Fashion and You",
"BrandList": " Nike, Fila",
"MerchantImage": "Fashion-You-medium.jpeg"
},
{
"MerchantName": "Fashion and You",
"BrandList": " Levis, Fasttrack, Fila",
"MerchantImage": "Fashion-You-medium.jpeg"
},
{
"MerchantName": "ebay",
"BrandList": "Nokia,HTC,Samsung",
"MerchantImage": "ebay.jpeg"
},
{
"MerchantName": "amazon",
"BrandList": "Apple,Dell,Samsung",
"MerchantImage": "amazon.jpeg"
},
{
"MerchantName": "amazon",
"BrandList": " pepe jeans, peter england, red tape",
"MerchantImage, Fila": "amazon.jpeg"
}
]
我需要使用Unique BrandList创建一个json对象,如下面的下划线所示。
[{"Nike"}, {"Fila"},{"Levis"}, {"Fasttrack"},{"Nokia"}, {"HTC"},{"Samsung"}, {"pepe jeans"}, {"peter england"},{"red tape"}]
我可以获得如下数据而不是上述格式,品牌必须是唯一的。
brands = [{brand:"Nike",status:false}, {brand:"Fila",status:false}, {brand:"Levis",status:false},{brand:"Fasttrack",status:false}, {brand:"Nokia",status:false},{brand:"HTC",status:false}, {brand:"Samsung",status:false} ]
答案 0 :(得分:1)
var col = [
{
"MerchantName": "Fashion and You",
"BrandList": " Nike, Fila",
"MerchantImage": "Fashion-You-medium.jpeg"
},
{
"MerchantName": "Fashion and You",
"BrandList": " Levis, Fasttrack, Fila",
"MerchantImage": "Fashion-You-medium.jpeg"
},
{
"MerchantName": "ebay",
"BrandList": "Nokia,HTC,Samsung",
"MerchantImage": "ebay.jpeg"
},
{
"MerchantName": "amazon",
"BrandList": "Apple,Dell,Samsung",
"MerchantImage": "amazon.jpeg"
},
{
"MerchantName": "amazon",
"BrandList": " pepe jeans, peter england, red tape",
"MerchantImage, Fila": "amazon.jpeg"
}
];
var brands = [];
//get unique brands
_.each(col, function(i){
brands = _.union(brands,i.BrandList.split(','));
});
//build output
brands = _.map(brands, function(brand){
return { brand : brand, status : false};
});
console.log(brands);
//if you need json output
var brandsJson = JSON.stringify(brands);
console.log(brandsJson);
答案 1 :(得分:0)
如上所述,您列出的json对象无效。如果您正在寻找一种方法来填充一系列独特的品牌名称,您可以使用一些下划线函数 -
var arr = ...;
function trim(str){
return str.replace(/^\s+|\s+$/g, "");
}
var mapped = _.map(_.pluck(arr, 'BrandList'), function(type){
return _.map(type.split(","), function(brand){
return trim(brand);
});
});
var unique = _.uniq(_.flatten(mapped));
//outputs ["Nike", "Fila", "Levis", "Fasttrack", "Nokia", "HTC", "Samsung", "Apple", "Dell", "pepe jeans", "peter england", "red tape"]
我不确定这是一个简单的循环更容易阅读,它在过程中创建了几个中间数组,但它完成了工作。