0

Given this structure:

{  
    "foo":{  
        "bar":{  
            "baz":[  
                {  
                    "foo bar":"baz",
                    "baz foo":"bar"
                }
            ]
        }
    }
}

How can I select 'foo bar' from a variable such as:

var myString = "baz[0]['baz foo']";

There are many examples of how to do it using dot notation:

Accessing nested JavaScript objects with string key

Access / process (nested) objects, arrays or JSON

Reference Nested JavaScript Object

But none of them support key with spaces in it seems.

An example JS fiddle

Community
  • 1
  • 1
Kiksy
  • 1,272
  • 5
  • 20
  • 43

2 Answers2

3

baz is an array of objects

var obj = {  
    "foo":{  
        "bar":{  
            "baz":[  
                {  
                    "foo bar":"baz",
                    "baz foo":"bar"
                }
            ]
        }
    }
};
var myString = obj.foo.bar.baz[0]['baz foo'];
alert(myString);

Updated
you can use .eval() method.

var obj = {  
    "foo":{  
        "bar":{  
            "baz":[  
                {  
                    "foo bar":"baz",
                    "baz foo":"bar"
                }
            ]
        }
    }
};
var myString = "obj.foo.bar.baz[0]['baz foo']";
alert(eval(myString));
ozil
  • 6,930
  • 9
  • 33
  • 56
2

The problem is with parsing the path of properties, as using split ignores the [] and the "". This regex prop.match(/[^.\[\]'"]+/g) extracts all props (fiddle):

function getProperty(obj, prop) {
    var parts = prop.match(/[^.\[\]'"]+/g),
        i = 0,
        current = parts[0];

    var currentValue = obj;

    while (currentValue[current]) {
        currentValue = currentValue[current];

        current = parts[++i];
    }

    if(i < parts.length) {
        return undefined;
    }

    return currentValue;
}

I'm sure that I didn't get all edge cases, and errors, but that's a good place to start. You should also check lodash _.get, which does exactly that.

Ori Drori
  • 183,571
  • 29
  • 224
  • 209