0

我有一个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} ]
4

2 回答 2

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);

源代码http://jsfiddle.net/DvnvN/

于 2013-08-25T09:02:26.147 回答
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"]

我不确定这是否比一个简单的循环更容易阅读,它会在该过程中创建几个中间数组,但它可以完成工作。

于 2013-08-26T00:15:44.330 回答