gpt4 book ai didi

javascript - 如何在 JAVASCRIPT 中更新数组及其对象

转载 作者:行者123 更新时间:2023-11-30 10:04:23 24 4
gpt4 key购买 nike

我有一个收集对象的数组。我想实现插入操作函数,它获取一些路径数组“idsListPath”和我们要插入的新对象“itemToInsert”。

示例:

function InsertIntoDataSet(idsListPath, itemToInsert)
//idsListPath: the path where i want to add "itemToInsert" object
{
//How do i push the itemToInsert in correct path?
}

示例数据:

var idsListPath = ["1", "3", "44"];
var itemToInsert = { id: "111", node: [] };
var dataSet = [{
id: "1", node: [
{
id: "98",
node: []
},
{
id: "3",
node: [{
id: "44",
node: [] //TARGET LOCATION TO PUSH THE NEW ITEM
}]
}]
},
{
id: "3",
node: []
},
{
id: "44",
node: []
}];

在示例中,我们的路径是“1”、“3”、“44”...

所以新的对象项应该插入到 ID 为“1”的对象的数据集中 > 它的 ID 为“3”的子节点 > 它的 ID 为“44”的子节点 > 在节点 [] 下我想推送新的对象项.

我怎样才能做到这一点?即使“idsListPath”数组具有单个值,该函数也应该起作用。

最佳答案

这是实现您需要的InsertIntoDataSet的实现:

function InsertIntoDataSet(idsListPath, itemToInsert)
{
var currentNode = dataSet;

for(var idx in idsListPath) {
var id = idsListPath[idx];

if(currentNode = findChildArrayByNodeId(currentNode, id)) {
continue;
}
else {
return;
}
}

if(currentNode) {
currentNode.push(itemToInsert);
}
}

function findChildArrayByNodeId(nodeArray, id) {
var node = nodeArray.filter(function(el) {
return el.id == id;
})[0];

return node ? node.node : undefined;
}

参见 live example .

关于javascript - 如何在 JAVASCRIPT 中更新数组及其对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30049465/

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