gpt4 book ai didi

javascript - 对具有多个条目的对象数组进行排序

转载 作者:行者123 更新时间:2023-12-02 19:11:49 26 4
gpt4 key购买 nike

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

最佳答案

我不知道你测试过什么样的循环,但是这种类型的代码对于要做的事情来说并不算长:

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

关于javascript - 对具有多个条目的对象数组进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13628320/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com