gpt4 book ai didi

javascript - 将条目附加到嵌套数组中

转载 作者:行者123 更新时间:2023-11-29 19:13:02 25 4
gpt4 key购买 nike

本质上,我试图得到一个如下所示的数组:

{
"projects" : [{
"project" : "Project One",
"tasks" : [{
"name" : "Task One"
}, {
"name" : "Task Two"
}, {
"name" : "Task Three"
}]
}, {
"project" : "Project Two",
"tasks" : [{
"name" : "Task One"
}, {
"name" : "Task Two"
}]
}]
}

我目前有以下数组和一个脚本,它查看任务的每个元素并检查它是否已经在项目名称列表中,如果不在,则插入第一个,应该 如果是,则添加第二个元素,但这就是我有点卡住的地方:

var tasks = [{
"name" : "Task One",
"project" : "Project One"
}, {
"name" : "Task One",
"project" : "Project Two"
}, {
"name" : "Task Two",
"project" : "Project One"
}, {
"name" : "Task Three",
"project" : "Project One"
}, {
"name" : "Task Two",
"project" : "Project Two"
}]


var projectNames = [];
var projects = [];
for ( i = 0; i < tasks.length; i++) {
if (projectNames.indexOf(tasks[i].project) < 0) {
// checks to see that it's not the projectNames list, and inserts the first entry
projectNames.push(tasks[i].project);
projects.push({
project : tasks[i].project,
tasks : {
name : tasks[i].name
}
});
} else {
// if that project is already in the list, append the next entry
var ind = projectNames.indexOf(tasks[i].project);
projects[ind].tasks.push({
name : tasks[i].name
});
}
}

我的印象是无法使用 projects[ind].tasks.push(),但我不确定用什么来替换它才是正确的?

(同样,如果有任何更好的方法从第一个数组到第二个数组,我总是很乐意学习新东西)

最佳答案

你可以使用 Array#forEach如果已经创建了相同的项目,则对于 thisArg 是一个对象。

var object = { "tasks": [{ "name": "Task One", "project": "Project One" }, { "name": "Task One", "project": "Project Two" }, { "name": "Task Two", "project": "Project One" }, { "name": "Task Three", "project": "Project One" }, { "name": "Task Two", "project": "Project Two" }] },
result = { projects: [] };

object.tasks.forEach(function (a) {
if (!this[a.project]) {
this[a.project] = { project: a.project, task: [] };
result.projects.push(this[a.project]);
}
this[a.project].task.push({ name: a.name });
}, Object.create(null));

console.log(result);

关于javascript - 将条目附加到嵌套数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37384838/

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