我有一个以下格式的 json 对象数据。因为我需要在特定 id 之后插入一些新记录。
[
{
"id":"1",
"name":"one",
"children":[
{
"id":"4",
"name":"four",
"children":[
]
},
{
"id":"5",
"name":"five",
"children":[
]
},
{
"id":"6",
"name":"six",
"children":[
]
}
]
}
]
例如:我的 id 为 5,还有 new 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/