I would start by changing your data structure. It's hard to see how the current format would be overly useful for iterating, aggregating, getting the user's name, getting the item's names, etc., without excessive iterating.
Here is one alternative data structure that is much easier to work with because it doesn't have nested arrays and doesn't require Object.keys
to access data you need consistently (e.g. user name):
var data = [{
user: 'Amy',
items: {
shirt: 12,
trouser: 10
}
}, {
user: 'Bill',
items: {
shirt: 10,
trouser: 11
}
}, {
user: 'Chet',
items: {
shirt: 11,
trouser: 12
}
}];
With this format, you could easily sort by a particular item quantity:
let getTopItem = (data, itemName) => {
// 1. clone the array using concat
// 2. sort by value at supplied itemName
// 3. return the first item
let sorted = data.concat().sort((a, b) => {
return b.items[itemName] - a.items[itemName];
});
return sorted.shift();
}
let topShirts = getTopItem(data, 'shirt');
console.log(topShirts.user);
EDIT - I don't mean this negatively toward any of the answers as they all seem to be correct and useful approaches to getting the required data from the presented data structure - but look at how many iterations they all require to get this very basic data out of your object. Choosing the right structure for your data will save you a lot of headaches down the road.