带过滤器的 JS 对象解构

JS Object Destructuring with Filter

我有一个对象的对象,我想通过对象中的键值来过滤。例如,我的对象看起来像:

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
  }
};

我希望能够按 creditid 过滤对象。例如,我想要 return 一个包含所有 creditid 为 "yyyy" 的对象的对象。

var { creditid: "yyyy" } = Financials;

结果如下:

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

这可以使用解构吗?

为此,您必须遍历每个 属性 财务,如下所示:

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 resultFinancials = {};

for (var financial in Financials) {
    if (Financials.hasOwnProperty(financial)) {
        if(Financials[financial] && Financials[financial].creditid =='yyyy' ){
            resultFinancials[financial] = Financials[financial];
        }
    }
}

console.log(resultFinancials)

就解构而言,我不知道这是否可以完成,只是因为解构更像 [​​=11=] 而不是 .filter()。但是,您实际上可以使用 .reduce() 函数轻松完成此操作,如下所示:

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);

您可以只过滤对象条目,然后将其映射回新对象

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
  }
};

let arr    = Object.entries(Financials).filter( set => set[1].creditid === "yyyy");
let result = Object.assign(...arr.map(d => ({[d[0]]: d[1]})))

console.log(result)
.as-console-wrapper {top:0; max-height: 100%!important}