gpt4 book ai didi

javascript - 在Javascript中寻找一种将具有重复数据的列样式数组转换为对象的方法

转载 作者:行者123 更新时间:2023-11-29 18:46:06 24 4
gpt4 key购买 nike

我正在尝试将如下所示的数组转换为数组下方对象的结构。

我已经尝试了很多东西,我也会在下面列出。但我觉得我的做法是错误的。并希望得到一些帮助。

var array = [
["plan_a", "tester_a", "product", "foo", "blocked", "5"],
["plan_a", "tester_a", "product", "foo", "passed", "10"],
["plan_a", "tester_a", "subproduct", "client", "passed", "15"],
["plan_a", "tester_b", "product", "bar", "blocked", "5"],
["plan_a", "tester_b", "product", "bar", "passed", "10"],
["plan_a", "tester_b", "subproduct", "server", "failed", "5"],
["plan_a", "tester_b", "subproduct", "server", "passed", "5"],
["plan_a", "tester_c", "product", "foo", "failed", "5"]
];

var object = {
plan_a: {
tester_a: {
product: {
product: "foo",
blocked: "5",
passed: "10"
},
subproduct: {
subproduct: "client",
passed: "15"
}
},
tester_b: {
product: {
product: "bar",
blocked: "5",
passed: "10"
},
subproduct: {
subproduct: "server",
failed: "5",
passed: "5"
}
},
tester_c: {
product: {
product: "foo",
failed: "5"
}
}
}
};

我试过这个:

var object = {}
var combining_plans =[]
var first_row = arr[0][0];

for (var i = 0; i < arr.length; i++) {
if (arr[i][0] == first_row) {
object[arr[i][0]] = [];
arr[i].shift();
combining_plans.push(arr[i]);
}
}

object[first_row] = combining_plans;

这会检查第一列是否相同,如果第一个元素将它变成对象的第一个键,然后将值添加为数组的所有剩余元素。

我曾考虑过为每个专栏反复这样做,但我觉得这可能行不通,而且还有比这样做更优雅的方法。

最佳答案

const array = [
["plan_a", "tester_a", "product" ,"foo" ,"blocked", "5" ],
["plan_a", "tester_a", "product" ,"foo" ,"passed" , "10" ],
["plan_a", "tester_a", "subproduct","client","passed" , "15" ],
["plan_a", "tester_b", "product" ,"bar" ,"blocked", "5" ],
["plan_a", "tester_b", "product" ,"bar" ,"passed" , "10" ],
["plan_a", "tester_b", "subproduct","server","failed" , "5" ],
["plan_a", "tester_b", "subproduct","server","passed" , "5" ],
["plan_a", "tester_c", "product" ,"foo" ,"failed" , "5" ],
];
const result = {};
array.forEach((item) => {
const [plan, tester, type, name, key, value] = item;
if(!result[plan]) {
result[plan] = {};
}
if(!result[plan][tester]) {
result[plan][tester] = {};
}
if(!result[plan][tester][type]) {
result[plan][tester][type] = {[type]: name};
}
Object.assign(result[plan][tester][type], {[key]: value});
});
console.log(result);

关于javascript - 在Javascript中寻找一种将具有重复数据的列样式数组转换为对象的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53856516/

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