0

我想在 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 循环遍历每个对象,但是如何以一种好的方式处理对象数组中的字符串数组?

4

2 回答 2

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]);
}
于 2012-11-29T15:10:55.027 回答
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];
});
于 2012-11-29T15:24:05.797 回答