javascriptarraysjsonfilterjsobject

How to filter records based on the status value in JavaScript object?


I have JS object that looks like this:

{
  "3": {
    "id": 3,
    "first": "Lisa",
    "last": "Morgan",
    "email": "lmorgan@gmail.com",
    "phone": "(508) 233-8908",
    "status": 0
  },
  "4": {
    "id": 4,
    "first": "Dave",
    "last": "Hart",
    "email": "dhart@gmail.com",
    "phone": "(509) 874-9411",
    "status": 1
  }
}

I would like to filter through the object and for example pull only record which status is '1'. One solution for that is to use array filter like this:

var filterJSON = Object.values(obj).filter(function (entry) {
                switch(frmFilter){
                    case '1':
                        return entry.status === 1;
                        break;
                    case '2':
                        return entry.status === 0;
                        break;
                    default:
                        return entry;
                }
            });

problem is code above will convert data into array like this:

[
  {
    "id": 3,
    "first": "Lisa",
    "last": "Morgan",
    "email": "lmorgan@gmail.com",
    "phone": "(508) 233-8908",
    "status": 1
  },
  {
    "id": 4,
    "first": "Dave",
    "last": "Hart",
    "email": "dhart@gmail.com",
    "phone": "(509) 874-9411",
    "status": 1
  }
]

As you can see data set is an array, I want to keep my data in object same as one in the first example before filter was applied. Is there a way to filter through the object and achieve the same output as one with filtering through array?


Solution

  • You can use .filter() with .reduce() to convert the filtered array back into an object:

    var obj = {
      "3": {
        "id": 3,
        "first": "Lisa",
        "last": "Morgan",
        "email": "lmorgan@gmail.com",
        "phone": "(508) 233-8908",
        "status": 0
      },
      "4": {
        "id": 4,
        "first": "Dave",
        "last": "Hart",
        "email": "dhart@gmail.com",
        "phone": "(509) 874-9411",
        "status": 1
      }
    }
    
    var frmFilter = "1";
    
    var filterJSON = Object.keys(obj).filter(function (key) {
        let entry = obj[key];
        switch(frmFilter){
            case '1':
                return entry.status === 1;
                break;
            case '2':
                return entry.status === 0;
                break;
            default:
                return entry;
        }
    }).reduce( (res, key) => (res[key] = obj[key], res), {} );
    
    console.log(filterJSON);

    Had some help from this answer: JavaScript: filter() for Objects