gpt4 book ai didi

javascript - 比较数组并删除对象

转载 作者:行者123 更新时间:2023-12-01 01:56:59 25 4
gpt4 key购买 nike

下面有这段代码,我试图通过比较图表来删除整行{"id": "Apple", "group": 1}使用 testArray 查看 graphtestArray 共有的每个对象,只需删除整行即可。但我不太确定如何完成删除它任何帮助将不胜感激

var graph = {   "nodes": [
{"id": "Apple", "group": 1},
{"id": "Cherry", "group": 2},
{"id": "Tomato", "group": 3}
],
"links": [
{"source": "Apple", "target": "Cherry", "value": 1},
{"source": "Cherry", "target": "Tomato", "value": 1},
{"source": "Tomato", "target": "Apple", "value": 1}
]
};

var testArray = ['Apple'];

var nodes = graph["nodes"];
let removeNodes = nodes;
removeNodes.forEach((obj) => {
if (testArray.includes(obj.id.toString()))
});

最佳答案

如何循环 testArray 并找到节点数组中的每个项目并将其删除?

编辑:如果您想通过给定键删除,您可以创建一个接受对象键和列表的函数。

var graph = {
nodes: [
{
id: "Apple",
group: 3
},
{
id: "Cherry",
group: 3
},
{
id: "Tomato",
group: 3
},
{
id: "Lemon",
group: 4
},
{
id: "Grape",
group: 5
}
],
links: [
{
source: "Apple",
target: "Cherry",
value: 1
},
{
source: "Cherry",
target: "Tomato",
value: 1
},
{
source: "Tomato",
target: "Apple",
value: 1
},
{
source: "Lemon",
target: "Grape",
value: 1
},
{
source: "Grape",
target: "Lemon",
value: 1
}
]
};

function removeObject(key, arr) {
arr.forEach((item) => {
// get all nodes that has the value of item
const foundNodes = graph.nodes.filter(node => arr.includes(node[key]));
// get index of each found item
foundNodes.forEach((node) => {
const nodeIndex = graph.nodes.indexOf(node);
// remove item by index
graph.nodes.splice(nodeIndex, 1);
})
});
}


// find object by group
removeObject('group', [3]);
console.log(graph);

关于javascript - 比较数组并删除对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50939359/

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