Search code examples
javascriptmultidimensional-arraymatchkey-valuemap-function

How can I extract object values from 3 nested json arrays by matched string object values from a separate array and then display it in html/javascript


I would like to match the "title" and "thumbnail" values from one json response array to the values in another response array and show them in an html list. Essentially I'm matching a multidimensional array by regEx to another array and then I'm trying to display the content in a list like the one at the bottom. Any help is appreciated.

Here is the 1st Array

jsonArray = [
  [{
    "position": "1",
    "title": "player 1",
    "thumbnail": "www.picuture.com/jpeg"
  }, {
    "position": "2",
    "title": "player 1",
    "thumbnail": "www.picuture2.com/jpeg"
  }],
  [{
    "position": "1",
    "title": "player 2",
    "thumbnail": "www.picuture.com/jpeg"
  }, {
    "position": "2",
    "title": "player 2",
    "thumbnail": "www.picuture2.com/jpeg"
  }],
  [{
    "position": "1",
    "title": "player 3",
    "thumbnail": "www.picuture1.com/jpeg"
  }, {
    "position": "2",
    "title": "player 3",
    "thumbnail": "www.picuture2.com/jpeg"
  }]
]

Below is the the second array it needs to match to

array2 = ["player1_details", "player2_details", "player3_details"]

I would like to have a html list with the title and image values from the jsonArray and the player details from array2.

example:
<ul>
  <li>player 1 </li><li>www.picuture1.com/jpeg" </li><li>player1_details </li>
  <li>player 2 </li><li>www.picuture2.com/jpeg" </li><li>player2_details </li>
  <li>player 3 </li><li>www.picuture3.com/jpeg" </li><li>player3_details </li>
</ul> 

Solution

  • So you can do it like this to get player details from position 1 as discussed in comments, its one of the many ways, I have defined a class with required attributes and pushed class object into a list. After this you can use this list to show the details however you want

    
    class reqInformation {
      constructor(title, thumbnail, details) {
        this.title = title;
        this.thumbnail = thumbnail;
        this.details = details;
      }
    }
    p = new reqInformation("titletest","thumbnailtest","detailstest");
    var finalList=[]
    var loopCount = 0;
    const itemPos = 1;
    
    
    
    Object.keys(jsonArray).forEach(function(key) {
        var matchText = jsonArray[key][itemPos]['title'].replace("player ", "");
        if(array2[loopCount].includes(matchText)){
            var p = new reqInformation(
                jsonArray[key][itemPos]['title'],
                jsonArray[key][itemPos]['thumbnail'],
                array2[loopCount]);
        }
        finalList.push(p)
        loopCount++
    });
    console.log(finalList)
    
    

    change itemPos to 0 if you want object at position 0