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

4
  • Correct myString to this - foo.bar.baz[0]['baz foo'] Commented Aug 13, 2015 at 11:08
  • Sorry I obviously didn't explain the question well enough, the string was just an example, I'll need to recurse over the object Commented Aug 13, 2015 at 11:11
  • Your question is still not very clear. Try to elaborate and present a test case. Commented Aug 13, 2015 at 11:14
  • @OriDrori added JSFiddle Commented Aug 13, 2015 at 11:18

2 Answers 2

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));

Sign up to request clarification or add additional context in comments.

1 Comment

Updated the string to explain more, assume my variable is as above
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.