0

Let's say I have a JSON object that looks like this, called "prices"

"Scrap Metal": {
            "defindex": [
                5000
            ],
            "prices": {
                "3": {
                    "Tradable": {
                        "Craftable": {
                            "0": {
                                "currency": "keys",
                                "value": 432,
                                "last_update": 1425334795,
                                "difference": 3491.64
                            }
                        }
                    }
                },
                "6": {
                    "Tradable": {
                        "Craftable": {
                            "0": {
                                "currency": "metal",
                                "value": 0.11,
                                "last_update": 1336410088,
                                "difference": 0
                            }
                        }
                    }
                }
            }
        },

This continues like this with a similar structure but different values. I want to search for the defindex: 5000 value and then get the value from 6 from it. In other words, if I knew where it was in the code by searching the defindex, I would call "name".prices[6].Tradable.Craftable[0].value.

I've tried to use underscore.js for this, but it didn't work. My code was: _.where(prices, { defindex: '5000' });

Any help would be appreciated. Thanks!

kjsmita6
  • 458
  • 1
  • 6
  • 21
  • 1
    Are you getting the JSON response from a server request or is this a variable defined in JavaScript? If it's the latter, it shouldn't be called JSON: http://stackoverflow.com/questions/3975859/what-are-the-differences-between-json-and-javascript-object – Qantas 94 Heavy Jul 23 '15 at 00:44
  • @Qantas94Heavy it's from a server. Specifically http://backpack.tf/api – kjsmita6 Jul 23 '15 at 00:45
  • 1
    how do you map defIndex 5000 to value 6 (instead of say, 3, for instance) – Sebas Jul 23 '15 at 00:47
  • You might want to take a look at this question: [Access / process (nested) objects, arrays or JSON](http://stackoverflow.com/questions/11922383/access-process-nested-objects-arrays-or-json). Please let me know if that answers your question. Thanks! – Qantas 94 Heavy Jul 23 '15 at 00:47

2 Answers2

1

I'd use #find which allows you to use a function, iterates over each key/value pair, where the value will be what the top key points to.

_.find(prices, function(value, key) { 
  return (value.defindex == "5000")
})
adzdavies
  • 1,545
  • 1
  • 13
  • 13
0

Since you might have a wide variety of possible queries and you're using underscore, you might like https://github.com/davidgtonge/underscore-query, as it provides Mongo-like query syntax:

prototype
  • 7,249
  • 15
  • 60
  • 94