gpt4 book ai didi

Javascript 数组到对象

转载 作者:数据小太阳 更新时间:2023-10-29 04:38:20 25 4
gpt4 key购买 nike

我有一个数组,如下所示:

files = [
'Dashboard/Logs/Errors',
'Dashboard/Logs/Other',
'Accounts/Main',
]

我想让它看起来像这样:

navigation = [
{
"title": "Dashboard",
"dropdown": [
{
"title": "Logs",
"dropdown": [
{
"title": "Errors",
},
{
"title": "Other",
}
]
}
]
},
{
"title": "Accounts",
"dropdown": [
{
"title": "Main",
}
]
}
]

到目前为止,我有以下内容:

var navigation = [];
for (var i = 0; i < files.length; i++) {
var parts = files[i].split('/');
navigation.push({title: parts[0]});
for (var j = 1; j < parts.length; j++) {

}
}

我很难找到一个合适的方法来做到这一点。到目前为止,我所拥有的已经不起作用,因为它在导航下创建了两个对象,每个对象都带有 title: "Dashboard"。任何聪明方法的想法?谢谢:)

最佳答案

这应该会产生所需的输出:

var files = [
'Dashboard/Logs/Errors',
'Dashboard/Logs/Other',
'Accounts/Main',
];

var navigation = [];
// Iterates through a navigation array and returns the object with matching title, if one exists.
var getNavigationObject = function(nav, title) {
for (var i = 0; i < nav.length; i++) {
if (nav[i].title == title) {
return nav[i];
}
}
};
// Adds a file to the nav.
// The input is an array of file components (i.e. file.split('/'))
// This works by recursively adding each component of a file.
var addToNav = function (nav, components) {
var n = getNavigationObject(nav, components[0]);
if (!n) {
n = {
title: components[0]
};
nav.push(n);
}
if (components.length > 1) {
n.dropdown = n.dropdown || [];
addToNav(n.dropdown, components.slice(1));
}
};

// Actually call `addToNav` on each file.
files.forEach(function(e) {
addToNav(navigation, e.split('/'));
});

// Produces the result in string form.
JSON.stringify(navigation, null, 2)

这通过递归检查给定元素是否已经与文件的组件匹配来工作。如果是这样,它会重新出现在该组件的“下拉列表”中。否则,它会创建它。

关于Javascript 数组到对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35493560/

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