gpt4 book ai didi

javascript - 插入/导航嵌套的 JavaScript 对象/数组

转载 作者:行者123 更新时间:2023-11-29 15:22:57 24 4
gpt4 key购买 nike

我有这个数据:

const items = [
{
_id: 0,
content: 'Item 1 something',
note: 'Some note for item 1'
},
{
_id: 5,
content: 'Item 1.1 something',
note: 'Some note for item 1.1'
},
{
_id: 1,
content: 'Item 2 something',
note: 'Some note for item 2',
subItems: [
{
_id: 2,
parent_id: 1,
content: 'Sub Item 1 something',
subItems: [{
_id: 3,
parent_id: 2,
content: 'Sub Sub Item 4'
}]
}
]
}
];

使用 Javascript,我如何导航/插入到树中,前提是我在任何时候都拥有树中一项的 _id。

例如一些案例场景:

  • 我在 _id 3 并且想插入另一个兄弟到 _id 3
  • 我在 _id 2 并想升至 _id 1 - 如何获得 _id 1?
  • 我在 _id 5,想去 _id 1

如何仅使用 _id 导航树?

最佳答案

您可以迭代数组并测试 _id 属性是否具有所需的值。然后保存节点、父节点或数组的下一项。

为了获取父节点,实际的父节点被保存为一个闭包,并在找到所需的 _id 时返回。

所有函数都将 subItems 作为数组进行测试,如果是,则对 subItems 执行迭代。

function getNode(array, id) {
var node;
array.some(function iter(a) {
if (a._id === id) {
node = a;
return true;
}
return Array.isArray(a.subItems) && a.subItems.some(iter);
});
return node;
}

function getParent(array, id) {
var parent ;
array.some(function iter(p) {
return function (a) {
if (a._id === id) {
parent = p;
return true;
}
return Array.isArray(a.subItems) && a.subItems.some(iter(a));
};
}(undefined));
return parent;
}

function getNextNode(array, id) {
var node;
array.some(function iter(a, i, aa) {
if (a._id === id) {
node = aa[i + 1];
return true;
}
return Array.isArray(a.subItems) && a.subItems.some(iter);
});
return node;
}

var items = [{ _id: 0, content: 'Item 1 something', note: 'Some note for item 1' }, { _id: 5, content: 'Item 1.1 something', note: 'Some note for item 1.1' }, { _id: 1, content: 'Item 2 something', note: 'Some note for item 2', subItems: [{ _id: 2, parent_id: 1, content: 'Sub Item 1 something', subItems: [{ _id: 3, parent_id: 2, content: 'Sub Sub Item 4' }] }] }];

console.log(getNode(items, 3));
console.log(getParent(items, 2));
console.log(getNextNode(items, 5));
.as-console-wrapper { max-height: 100% !important; top: 0; }

关于javascript - 插入/导航嵌套的 JavaScript 对象/数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42063209/

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