gpt4 book ai didi

javascript - 根据另一个对象的数据创建一个对象(添加一个 "level")

转载 作者:行者123 更新时间:2023-12-02 22:49:43 25 4
gpt4 key购买 nike

在我光荣的循环失败后,我来到这里寻求帮助。
基本上我想根据源数据“添加新级别”到我的目标 JSON。

基础 JSON:

var base = [
{
children: [
{
children: [],
parent: "ROOT",
title: "Tenant1",
typeName: "Tenants"
},
{
children: [],
parent: "ROOT",
title: "Tenant2",
typeName: "Tenants"
}
],
parent: null,
title: "ROOT",
typeName: null,
}
];

目标 JSON:

var target = [
{
children: [
{
children: [
{
children: [],
parent: "Tenants",
title: "Tenant1",
typeName: "Tenants"
},
{
children: [],
parent: "Tenants", // <---- here
title: "Tenant2",
typeName: "Tenants"
}
],
parent: "ROOT", // <---- here
title: "Tenants",
typeName: "Tenants"
}
],
parent: null,
title: "ROOT",
typeName: null
}
];

新级别需要将父级设置为 ROOT,并且“旧”子级(现在为叶子)必须将父级设置为其“typeName”。

最佳答案

希望这对您有用。我创建了一个递归函数,一旦找到您传递来添加的元素的父元素,它就会将父元素的子元素传递给当前元素并添加新元素。

var base = [
{
children: [
{
children: [],
parent: "ROOT",
title: "Tenant1",
typeName: "Tenants"
},
{
children: [],
parent: "ROOT",
title: "Tenant2",
typeName: "Tenants"
}
],
parent: null,
title: "ROOT",
typeName: null,
},
];

let element = {
parent: "ROOT",
title: "Tenants",
typeName: "Tenants"
};

function addNewLevel(list, element) {
if(list.length) {
for (var i = 0; i < list.length; i++) {
if(list[i].title === element.parent) {
element.children = list[i].children;
for (var j = 0; j < element.children.length; j++) {
element.children[j].parent = element.title;
}
list[i].children = [element];
} else if(list[i].children.length) {
let newList = addNewLevel(list[i].children, element);
list[i].children = newList;
return list[i];
}
}
return list;
}
}

console.log('New Level List', addNewLevel(base, element));

关于javascript - 根据另一个对象的数据创建一个对象(添加一个 "level"),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58233296/

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