user1937021
user1937021

Reputation: 10781

sort a JavaScript/JSON object with Underscore

I wanted to sort the JSON file below by specifically the trouser's stock level of each product, but I'm not sure how to write the code using the function _.sortBy, I made a start but not sure how I specifically target the stock level of the trousers. It should be the lowest stock level first. Any ideas? Thanks!

SCRIPT:

var sortedArray = _.sortBy(templateData, function(stocklevel) {
    return stocklevel[0].looks
}); 

JSON:

var templateData = {
    listTitle: "Shop by Look",
    looks: [
        {
            id: "Sportswear Look 1",
            products: [
                {
                    name: "Shirt",
                    pid: "50",
                    stock_level: 1,
                    image: "img/look1.jpg"
                },
                {
                    name: "Trousers",
                    pid: "40",
                    stock_level: 7,
                    image: ""
                },
            ]
        },
        {
            id: "Sportswear Look 2",
            products: [
                {
                    name: "Shirt",
                    pid: "50",
                    stock_level:5,
                    image: "img/look2.jpg"
                },
                {
                    name: "Trousers",
                    pid: "40",
                    stock_level: 16,
                    image: ""
                },
            ]
        }
    ]
}

Upvotes: 0

Views: 2120

Answers (1)

Bergi
Bergi

Reputation: 664297

First of all, you need to sort the templateData.looks array, not the templateData wrapper object.

The iterator function given to sortBy will be called with each one of the sorted objects, i.e. the "shop" objects in here. When you want to return the stock level of the trousers, you need to get that object. If you don't know where it is, you will need to search it in the products array at first, Underscore's findWhere will help you with that.

var sortedArray = _.sortBy(templateData.looks, function(shop) {
    return _.findWhere(shop.products, {name:"Trousers"}).stock_level;
});

Upvotes: 1

Related Questions