Search code examples
javascriptecmascript-6

How to filter an array of objects by key


There are similar questions to this but I cannot find something to tackle this one exactly.

I have an Array that is shaped like this:

AllReviews: [

{"0001": [
         {"Review": "In a Pickle", "Notes": "Approved"},
         {"Review": "A Cat Nap", "Notes": "Approved"},
         {"Review": "Flea market", "Notes": "Approved"}
       ]
},
{"0002": [
         {"Review": "Mouth-watering", "Notes": "Approved"},
         {"Review": "Easy As Pie", "Notes": "Approved"},
       ]
},
{"0003": [
         {"Review": "Loved it", "Notes": "Approved"},
         {"Review": "To sweet", "Notes": "Rejected"}
       ]
}

]

I want to filter this Array so that it only returns the review for 002. I cannot figure out how to do it. My attempt was feeble:

AllReviews.value.filter((Review) => {
   for (const [Key, Value] of Object.entries(Review)) {
    return Review[Key] === 0002 // Trying to say return the value (the array with reviews and notes) where the Key of the object matches what I want e.g. 0002
 }
})

My code is a nonsense of course and will not work.


Solution

  • Simply:

    const AllReviews =
        [ { '0001': 
            [ { Review: 'In a Pickle', Notes: 'Approved'} 
            , { Review: 'A Cat Nap',   Notes: 'Approved'} 
            , { Review: 'Flea market', Notes: 'Approved'} 
          ] } 
        , { '0002': 
            [ { Review: 'Mouth-watering', Notes: 'Approved'} 
            , { Review: 'Easy As Pie',   Notes: 'Approved'} 
          ] } 
        , { '0003': 
            [ { Review: 'Loved it', Notes: 'Approved'} 
            , { Review: 'To sweet', Notes: 'Rejected'} 
        ] } ];
        
    const Result = AllReviews.filter( row => row.hasOwnProperty('0002') );
    
    console.log( Result );
    .as-console-wrapper{max-height:100% !important;top:0}
    .as-console-row::after{display:none !important;}