使用多个条目对对象数组进行排序

时间:2012-11-29 14:49:13

标签: javascript

我想在javascript中重新排列一个对象数组,如下所示:

[{ year: "1950-12-20", product: ["product 1", "product 2, "product 3"] }, { year: "1951-12-20", product: ["product 3", "product 2"] }, { year: "1952-12-20", product: ["product 3", "product 4"] }]

这样我就可以得到两个阵列,一个是产品,另一个是出现的年份。

a = ["product 1", "product 2", "product 3", "product 4"]
b = ["1950-12-20", [ "1950-12-20, "1951-12-20"],["1950-12-20", "1951-12-20", "1952-12-20"],"1952-12-20"]

我试图通过嵌套的for循环遍历每个对象,但是如何以一种很好的方式处理对象数组中的字符串数组呢?

2 个答案:

答案 0 :(得分:1)

我不知道你测试过什么类型的循环,但是这种类型的代码不是那么长时间才能完成:

var data = [{ year: "1950-12-20", product: ["product 1", "product 2", "product 3"] }, { year: "1951-12-20", product: ["product 3", "product 2"] }, { year: "1952-12-20", product: ["product 3", "product 4"] }];

var nbData = data.length, iData;
var years = [], products = [], dictProductsYear = {};
var nbProducts, iProduct, p;


// Loop through years
for(iData = 0; iData < nbData; iData ++) {
    products = data[iData].product;
    nbProducts = products.length;

    // Add the current year to the concerned products
    for(iProduct = 0; iProduct < nbProducts; iProduct ++) {
        p = products[iProduct];

        // Registered product
        if(dictProductsYear[p]) dictProductsYear[p].push(data[iData].year);
        // Unregistered one
        else dictProductsYear[p] = [ data[iData].year ];
    }
}

var yearList = [], productList = [];

// Flatten the dictionary in 2 lists
for(p in dictProductsYear) {
    productList.push(p);
    yearList.push(dictProductsYear[p]);
}

答案 1 :(得分:1)

这看起来有点像@Samuel Caillerie的代码,但更简洁:

var data = [{ year: "1950-12-20", product: ["product 1", "product 2", "product 3"] }, { year: "1951-12-20", product: ["product 3", "product 2"] }, { year: "1952-12-20", product: ["product 3", "product 4"] }];

var yearsByProd = {};
for (var i=0; i<data.length; i++) {
    var prod = data[i].product;
    for (var j=0; j<prod.length; j++) {
         if (prod[j] in yearsByProd)
             yearsByProd[prod[j]].push(data[i].year);
         else
             yearsByProd[prod[j]] = [data[i].year];
    }
}
var a, b;
b = (a = Object.keys(yearsByProd).sort()).map(function(prod) {
    // add an if-else-statement here if you want to extract single years from their array
    return yearsByProd[prod];
});