我想要通过对象中键的值来过滤对象的对象。例如,我的对象看起来像:
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过滤对象。例如,我想返回一个包含所有具有“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
}
}
这是否可以使用解构?
答案 0 :(得分:0)
为此,您必须遍历Financials的每个属性,如下所示:
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)
答案 1 :(得分:0)
就解构而言,我不知道这可以做到,只是因为解构更像.map()
而不是.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);

答案 2 :(得分:0)
您可以只过滤对象条目,然后将其映射回新对象
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}