How would I use the value of one element in an array to access another array in React?

Viewed 464

I have data from an API that is like:

[
    {
        "id": 1,
        "name": "eventName1",
        "related_events": [
            2,
            3
        ]
    },
    {
        "id": 2,
        "name": "eventName2",
        "related_events": [
            1,
            3
        ]
    },
    {
        "id": 3,
        "name": "eventName3",
        "related_events": [
            1,
            2,
            4
        ]
    }
]

Each element of the related_events array links to an id element. So, if the related_events has 2 and 3 then that means I have to call id 2 and 3.

If I want to get the name that corresponds to the related_events ids, how would I code it?

Example, if the related_events has 2 and 3 then I want to display the names "eventName2" and "eventName3".

1 Answers

You can search your data for the related_event ids by iterating through or by using Array.find function. Something like this:

const testData = [
    {
        "id": 1,
        "name": "eventName1",
        "related_events": [
            2,
            3
        ]
    },
    {
        "id": 2,
        "name": "eventName2",
        "related_events": [
            1,
            3
        ]
    },
    {
        "id": 3,
        "name": "eventName3",
        "related_events": [
            1,
            2,
            4
        ]
    }
];


// the object to test from the data
const testObject = testData[0];

//we iterate over every id of related_events
testObject.related_events.forEach(targetId => {
  
  //we search in the data for a matching element that corresponds to the related_event id
  const targetElement = testData.find(element => {return element.id === targetId});
  
  //check if that element actually exists, just to be sure
  if (!!targetElement) {
    console.log(targetElement.name);
  }
  else {
    console.log("no matching object found");
  }
});

There is really no difference when using React to just using basic javascript, as the logic is the same.

Related