views:

103

answers:

3

Given the following object graph:

{
"children": [
    {
        "child": {
            "pets": [
                {
                    "pet": {
                        "name": "fido"
                    }
                },
                {
                    "pet": {
                        "name": "fluffy"
                    }
                }
            ]
        }
    },
    {
        "child": {
            "pets": [
                {
                    "pet": {
                        "name": "spike"
                    }
                }
            ]
        }
    }
]

}

What would be a nice one-liner (or two) to collect the names of my grandchildren's pets? The result should be ["fido", "fluffy", "spike"]

I don't want to write custom methods for this... I'm looking for something like the way jQuery works in selecting dom nodes, where you can just give it a CSS-like path and it collects them up for you.

I would expect the expression path to look something like "children child pets pet name"

+2  A: 

Hi Kevin

LINQ to JavaScript (JSLINQ) is an implementation of LINQ to Objects implemented in JavaScript. It is built using a set of extension methods built on top of the JavaScript Array object. If you are using an Array, you can use LINQ to JavaScript.

LINQ to JavaScript is an open source project and you can download it from here: http://jslinq.codeplex.com/

Hope this helps...

Muse VSExtensions
Thanks, I'll check it out!
Kevin Pauli
Wow, that's a great library.
Pim Jager
Why on earth is this being flagged as spam?
Michael Myers
@mmyers good question. Maybe somebody doesn't like the idea of LINQ for javascript?
Randolpho
@mmyers: I didn't flag it, but I guess it's because it's signed with the name of an unrelated product.
interjay
A: 

If you don't want to use a library, this is the most concise way I could think of writing it.

var Ar=[];
p.children.map(function(a){a.child.pets.map(function(a){Ar.push(a.pet.name)})});
Tim
Appreciate the response! Unfortunately I was looking for something more intuitive (for maintenance purposes, you understand...)
Kevin Pauli
A: 

I settled on the JSONPath library, which is like XPath for JSON. LINQ seemed a little heavyweight for my needs, resulting in a more verbose syntax, though it does look more powerful. Perhaps if my needs change I'll upgrade.

Kevin Pauli