-2
[
    {
        "item": "1",
        "values": [{"name": "A"}]
    },
    {
        "item": "2",
        "values": [{"name": "B"}]
    },
    {
        "item": "3",
        "values": [{"name": "A"}]
    }
]

and the desired result is: ["A", "B"] grabbed from the name field

What's the "Javascript practice" of that? Thanks.

NSF
  • 2,499
  • 6
  • 31
  • 55
  • 1
    What have you tried? A basic for loop would iterate you through the object so you could obtain the values you want. What exactly is the problem? – scrappedcola Aug 29 '14 at 18:32
  • possible duplicate of [Access / process (nested) objects, arrays or JSON](http://stackoverflow.com/questions/11922383/access-process-nested-objects-arrays-or-json) – Matt Burland Aug 29 '14 at 18:33
  • Heh, if you think that's deep... just you wait brah. – Sterling Archer Aug 29 '14 at 18:34
  • 3
    Your list has some invalid syntax in it - the "values" property is set to an array instance that contains a ":" separator in it. – kinakuta Aug 29 '14 at 18:34

1 Answers1

0

First you have a syntax error in your nested array definition.

"values": ["name": "A"]  // this is not valid javascript

... I'm guessing you wanted something more like this?

x=[
    {
        "item": "1",
        "values": {"name": "A"}
    },
    {
        "item": "2",
        "values": {"name": "B"}
    },
    {
        "item": "3",
        "values": {"name": "A"}
    }
]

Second, to your real question - I would use either underscore JS or the Lodash library to help. In particular their map functions. So assuming you were using the object I defined above for x, and are using underscore JS...

.map(x, function(y){return y.values.name})
["A", "B", "A"]

Hope that helps.

michael salmon
  • 398
  • 4
  • 12
  • 1
    isn't "A" duplicated here? – NSF Aug 29 '14 at 19:14
  • Yes, because there are two value.name properties with "A". If you want to filter them and only get unique values there is another underscore.js function for that (coincidentally _.uniq()) – michael salmon Aug 30 '14 at 01:43