简体   繁体   中英

Extract JSON into Javascript variables

I'm new at javascript and here is a newbie question:

In php, there is an extract() method which can import variables from an associative array. For example:

$var_array = array("color" => "blue",
                   "size"  => "medium",
                   "shape" => "sphere");
extract($var_array);
// $color is a defined varible here with the value of "blue"

I wonder if there is a method in standard Javascript, or in popular libraries like jQuery or underscore, that does the same for a Javascript Object. I mean something like this:

jsObject = {"color" : "blue",
            "size"  : "medium",
            "shape" : "sphere"};

extract(jsObject); // Is there such a thing?

// Here, color is a defined variable

You can do something like this:

Object.getOwnPropertyNames(obj).forEach(k => window[k] = obj[k]);

Or to limit the scope of the new variables:

Object.getOwnPropertyNames(obj).forEach(k => this[k] = obj[k]);

You can use

function extract(jsObject){
    for (var key in jsObject) {
       window[key] = jsObject[key];
    }
}




 console.log(size)   //medium

There's nothing in standard Javascript that works quite like that but if you use ES6 you can destructure your objects like this

const obj = {
    color: 'blue',
    size: 'medium',
    shape: 'sphere',
}

const { color, size, shape } = obj;

console.log(color, size, shape) // blue medium sphere

You can use Babel to transpile your code to ES6. It may be a little advanced for you now if you're just starting out so I recommend you stick with the intuitive approach but after a few weeks definitely check out Babel. It gives you some really cool stuff.

There are 2 problems with using window object:

  1. It, and all of its properties are default global variables. Which may not be in interest.

  2. There must be an assumption that it exists in all browsers (which it is now). Think about Nodejs

You can do:

for (var key in jsObject) {
    eval('var ' + key + ' = ' + jsObject[key]);
}

Try this, might help:

(function () {
    var jsObject = {color: 'blue'};

    // Dynamically assign to local variables
    for (var key in jsObject) {
        eval('var ' + key + ' = ' + jsObject[key]);
    }

    // Test locally
    console.log(color);
})();

// Test globally
console.log(color);

Results:

'blue'
[error] color is not defined

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