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?
For that you have to iterate through each property of Financials, as follows:
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)
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);
You could just filter the objects entries, and then map it back to new object
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}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.