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"] }]

1 つは製品、もう 1 つは製品が登場した年です。

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

これは @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 に答える
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 に答える