Search code examples
javascriptfilterjavascript-objectsdestructuring

JS Object Destructuring with Filter


I have an object of objects I want to filter via the value of a key in the objects. For example, my object looks like:

const Financials = {
  xxxxx: {
    creditid: "yyyy",
    aggRevs: 2000,
    aggexpenses: 1000,
    dateOf: 12 / 31 / 2015
  },
  zzzz: {
    creditid: "yyyy",
    aggRevs: 1000,
    aggexpenses: 1000,
    dateOf: 12 / 31 / 2016
  },
  aaaa: {
    creditid: "bbbb",
    aggRevs: 1000,
    aggexpenses: 1000,
    dateOf: 12 / 31 / 2016
  }
};

I want to be able to filter the object by creditid. For example, I want to return an object that contains all the objects that have a creditid of "yyyy".

var { creditid: "yyyy" } = Financials;

And the result would look like:

{
  xxxxx: {
    creditid: "yyyy",
    aggRevs: 2000,
    aggexpenses: 1000,
    dateOf: 12 / 31 / 2015
  },
  zzzz: {
    creditid: "yyyy",
    aggRevs: 1000,
    aggexpenses: 1000,
    dateOf: 12 / 31 / 2016
  }
}

Is this possible using destructuring?


Solution

  • As far as destructuring goes, I don't know that this can be done, simply because destructuring works more like .map() than .filter(). However, you can actually do this pretty easily with the .reduce() function, like so:

    const Financials = {
      xxxxx: {
        creditid: "yyyy",
        aggRevs: 2000,
        aggexpenses: 1000,
        dateOf: 12 / 31 / 2015
      },
      zzzz: {
        creditid: "yyyy",
        aggRevs: 1000,
        aggexpenses: 1000,
        dateOf: 12 / 31 / 2016
      },
      aaaa: {
        creditid: "bbbb",
        aggRevs: 1000,
        aggexpenses: 1000,
        dateOf: 12 / 31 / 2016
      }
    };
    
    var filtered = Object.keys(Financials).reduce((res, key) => {
      if (Financials[key].creditid === "yyyy") {
        res[key] = Financials[key]
      }
      return res;
    }, {});
    
    console.log(filtered);