Search code examples
javascriptarraysfindjavascript-objectskey-value

Return object with specific key:value pair in an array nested in another array - Javascript


I'm trying return an object from the code below that has the key value pair of name:sparky and return the entire metadata and stats array for that object.

I don't want to use Object.values(objectArray)[0] because this data is coming from an API and I expect the objects position in the array to change in the future.

I've tried objectArray.find but I don't know how to use that to find a value of an array which is inside another array. The value for name will always be unique and the actual objectArray has many more objects inside of it.

Help would be greatly appreciated!

Code

objectArray = [
  {
    "metadata": [
      {
        "key": '1',
        "name": "sparky"
      }
    ],
    "stats": [
      {
        "statsFieldOne": "wins"
      },
      {
        "statsFieldTwo": "kills"
      }
    ]
  },
  {
    "metadata": [
      {
        "key": '1',
        "name": "abby"
      }
    ],
    "stats": [
      {
        "statsFieldOne": "wins"
      },
      {
        "statsFieldTwo": "kills"
      }
    ]
  }
]

Desired result

     {
       "metadata": [
          {
            "key": '1',
            "name": "sparky"
          }
        ],
        "stats": [
          {
            "statsFieldOne": "wins"
          },
          {
            "statsFieldTwo": "kills"
          }
        ]
      }

Solution

  • I guess you can do following:

    function getObjectForName(key, name) {
        var filteredMetadata = [];
        for(var i=0; i< objectArray.length; i++) {
            filteredMetadata = objectArray[i].metadata.filter((val) => val[key] === name)
            if(filteredMetadata.length) {
                return objectArray[i];
            }   
        }
    }
    getObjectForName('name', 'sparky')
    

    What this code basically does is, iterates through all objects and check if name is sparky, if yes just break it. If you want to return all occurrences matching name, you need to add all of them to another array and return it.