简体   繁体   中英

JS get nested property of object with space in name

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

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM