Reputation: 677
I have some json data which looks like this:
{
'harry-test-com': { 'quoteID234324': {'day': 'tuesday', 'cost':'1000'}},
'sam-imaginarydomain-com': {
'quoteID13211': {'day': 'wednesday', 'cost': '500'},
'quoteID534534': {'day': 'monday', 'cost': '300'}
}
};
So basically our quotes are arranged by user for easy filtering. However, on one page I'd like to display ALL the quotes in a list. So I'd like to go through each user, grab their quotes, and add them to an object sorted by keys, like this:
'quoteID234324': {'day': 'tuesday', 'cost':'1000'},
'quoteID13211': {'day': 'wednesday', 'cost': '500'},
'quoteID534534': {'day': 'monday', 'cost': '300'}
I think lodash would no doubt be useful for this, but I just have no clue where to begin?? Any help would be GREATLY appreciated! Cheers
Upvotes: 1
Views: 84
Reputation: 192477
You can reduce the object into a new object using Object.keys()
and Object.assign()
:
const obj = {
'harry-test-com': {
'quoteID234324': {
'day': 'tuesday',
'cost': '1000'
}
},
'sam-imaginarydomain-com': {
'quoteID13211': {
'day': 'wednesday',
'cost': '500'
},
'quoteID534534': {
'day': 'monday',
'cost': '300'
}
}
};
const result = Object.keys(obj).reduce((days, user) => Object.assign(days, obj[user]), {});
console.log(result);
A less supported option is to use Object.values()
with Object.assign
:
const obj = {
'harry-test-com': {
'quoteID234324': {
'day': 'tuesday',
'cost': '1000'
}
},
'sam-imaginarydomain-com': {
'quoteID13211': {
'day': 'wednesday',
'cost': '500'
},
'quoteID534534': {
'day': 'monday',
'cost': '300'
}
}
};
const result = Object.assign({}, ...Object.values(obj));
console.log(result);
Upvotes: 1