0

i want to filter the following object

Provided Input

{
   "-Ms0hh73q83B7mlmlioU":{
      "address":"House#1",
      "contact":"999-999-999",
      "history":{
         "0":{
            "date":"28 Dec 2021"
         },
         "-Ms0hirc8slZ8-UsHU5Z":{
            "date":"28 Dec 2021"
         }
      },
      "name":"John"
   },
   "-Ms0hnbp2Nyu-HHonYdj":{
      "address":"House#2",
      "contact":"123-123-123",
      "history":{
         "0":{
            "date":"28 Dec 2021"
         },
         "-Ms0hoVTDDJdL-KzpIu5":{
            "date":"28 Dec 2021"
         }
      },
      "name":"Bill"
   }
}

I want to filter it on name = "John" and want the following output.

Required Output

{
"-Ms0hh73q83B7mlmlioU":{
      "address":"House#1",
      "contact":"999-999-999",
      "history":{
         "0":{
            "date":"28 Dec 2021"
         },
         "-Ms0hirc8slZ8-UsHU5Z":{
            "date":"28 Dec 2021"
         }
      },
      "name":"John"
   },

How can i filter this object to achieve my goal?

  • 1
    try - `obj[Object.keys(obj).find(key => obj[key].name === 'John')]` where `obj` is your starting object (https://jsfiddle.net/9s3ugb7x/1/) – andy mccullough Dec 28 '21 at 16:06
  • 2
    [Duplicate](//google.com/search?q=site:stackoverflow.com+js+filter+object+by+property+on+nested+object) of [Filter nested object](/q/61230284/4642212). Familiarize yourself with [how to process objects](/q/11922383/4642212) and how to [create objects](//developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Object_initializer) and use the available static and instance methods of [`Object`](//developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object#Static_methods) and [`Array`](//developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array#Static_methods). – Sebastian Simon Dec 28 '21 at 16:06
  • 1
    @andymccullough Since the question mentions _filtering_, `Object.fromEntries(Object.entries(theObject).filter(([ _key, { name } ]) => name === "John"))` seems more appropriate. – Sebastian Simon Dec 28 '21 at 16:08

0 Answers0