I'm new react developer, here i'm using 'react-d3-graph' to get my nodes and links, at the moment using 'info' i'm successfully getting 3 nodes and two links, those links connect to nodes. for example link with 'target:1' is connected to node 'id:1' and link with 'target:2' is connected to node 'id:2' (links and nodes could be many more than this). My question is, is there a way to filter this, if user clicks a button then from redux i'm getting 'testThis' object, that object shows currently clicked buttons 'identifier' and that identifier can be in those 'nodes' with the name of 'book_id', how to filter it, so that if 'nodes' contain 'book_id' which value is same as 'identifier' value then find it and select it. In this case it should select node which has book_id and its link with it(link with target 2) so with that user only can see two nodes and one link, is this possible ? so then Graph would be getting this : after button clicked:
{
links: [
{
id: 1,
source: 0,
target: 2,
color: 'green',
},
],
nodes: [
{
id: 0,
name: 'Camera',
x: 210,
y: 0,
},
{
book_id: 'gDUy',
id: 2,
name: 'livingRoom',
x: 400,
y: 210,
},
],
};
before button clicked:
import { Graph } from 'react-d3-graph';
const testThis ={
identifier: "gDUy",
}
const info = {
links: [
{
id: 0,
source: 0,
target: 1,
color: 'green',
},
{
id: 1,
source: 0,
target: 2,
color: 'green',
},
],
nodes: [
{
id: 0,
name: 'Camera',
x: 210,
y: 0,
},
{
id: 1,
name: 'Kitchen',
x: 0,
y: 210,
},
{
book_id: 'gDUy',
id: 2,
name: 'livingRoom',
x: 400,
y: 210,
},
],
};
<Graph
data={info}
/>
English is not my mother language so could be mistakes.
CodePudding user response:
const testThis = {
identifier: "gDUy",
}
const info = {
links: [{
id: 0,
source: 0,
target: 1,
color: 'green',
},
{
id: 1,
source: 0,
target: 2,
color: 'green',
},
],
nodes: [{
id: 0,
name: 'Camera',
x: 210,
y: 0,
},
{
id: 1,
name: 'Kitchen',
x: 0,
y: 210,
},
{
book_id: 'gDUy',
id: 2,
name: 'livingRoom',
x: 400,
y: 210,
},
],
};
function filterGraph() {
let nodes = info.nodes.filter(x => x.book_id == testThis.identifier);
let links = info.links.filter(x => nodes.map(y => y.id).includes(x.target));
let sourceNodes = info.nodes.filter(x => links.map(y => y.source).includes(x.id));
let allNodes = nodes.concat(sourceNodes);
console.log({links:links,nodes:allNodes});
}
filterGraph();