0

I want to found the ids connection with the help of name connection

this are my container elements

  const TotalNodes = [ 
                             {id : 1, name : "apple"},
                             {id : 2 , name : "banana"},
                             {id : 3 , name : "orange"},
                             {id : 4 , name : "lamon"},
                             {id : 5 , name : "suger"},
                             {id : 6 , name : "salt"}
                          ]

this is my reference array

const NodesConnection = [
                            {source : "suger" , target : "salt"},
                            {source : "apple" , target : "orange"}
                          ]

this is final output

 const NodesConnectionWithIds = [
                                   {source : 5 , target : 6},
                                   {source : 1 , target : 3}
                                 ]

any help is so appreciatable

jsBug
  • 348
  • 1
  • 9
  • 1
    Does this answer your question? [Find object by id in an array of JavaScript objects](https://stackoverflow.com/questions/7364150/find-object-by-id-in-an-array-of-javascript-objects) – derpirscher Mar 20 '22 at 09:52

1 Answers1

1

Here is a function that does the trick:

/**
 * 
 * @param {{id: number, name: string}[]} nodes
 * @param {{source: string, target: string}[]} connections
 * @returns {{source: number, target: number}[]}
 */
function matchNodes(nodes, connections) {
  return connections.map((connection) => {
    const source = nodes.find((node) => node.name === connection.source);
    const target = nodes.find((node) => node.name === connection.target);
    return {
      source: source.id,
      target: target.id,
    };
  });
}

console.log(matchNodes(TotalNodes, NodesConnection));
Ben
  • 1,331
  • 2
  • 8
  • 15