gpt4 book ai didi

javascript - 在嵌套的 json 对象中插入数据

转载 作者:行者123 更新时间:2023-11-30 20:20:28 28 4
gpt4 key购买 nike

我有一个以下格式的 json 对象数据。因为我需要在特定 ID 之后插入一些新记录。

    [
{
"id":"1",
"name":"one",
"children":[
{
"id":"4",
"name":"four",
"children":[

]
},
{
"id":"5",
"name":"five",
"children":[

]
},
{
"id":"6",
"name":"six",
"children":[

]
}
]
}
]

例如:我的 id 为 5,还有新的 JSON 对象({"id":"new data","name":"new data","children":[]})。那么新数据应该在 id 5 之后插入。是否有任何可能的方法在某个特定的 id 之后插入。

        [
{
"id":"1",
"name":"one",
"children":[
{
"id":"4",
"name":"four",
"children":[

]
},
{
"id":"5",
"name":"five",
"children":[

]
},
{
"id":"new data",
"name":"new data",
"children":[

]
},
{
"id":"6",
"name":"six",
"children":[

]
}
]
}
]

最佳答案

这是一个带有 splice 的快速示例 ;)只需传递目标数组、对象和 ID,add 函数就会将您的新对象插入到目标中的适当位置。

const data = [{
"id":"1",
"name":"one",
"children":[
{
"id":"4",
"name":"four",
"children":[]
},
{
"id":"5",
"name":"five",
"children":[]
},
{
"id":"6",
"name":"six",
"children":[]
}
]
}];

const object = {"id":"new data","name":"new data","children":[]};

const add = (object, toArray, afterId) => {
const afterIndex = toArray.findIndex(item => item.id === afterId);
toArray.splice(afterIndex + 1, 0, object);
};

add(object, data[0].children, '5');
console.log(data);

关于javascript - 在嵌套的 json 对象中插入数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51499520/

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