简体   繁体   English

将JSON提取到Javascript变量中

[英]Extract JSON into Javascript variables

I'm new at javascript and here is a newbie question: 我是javascript新手,这是一个新手问题:

In php, there is an extract() method which can import variables from an associative array. 在php中,有一个extract()方法可以从关联数组中导入变量。 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. 我想知道标准Javascript或流行的库(例如jQuery或下划线)中是否存在对Javascript对象执行相同方法的方法。 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 标准Javascript中没有什么可以像这样工作的,但是如果您使用ES6,则可以像这样破坏对象

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. 您可以使用Babel将您的代码转换为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. 如果您刚刚开始,那么现在对您来说可能有点高级,所以我建议您坚持使用直观的方法,但是几周后一定要检查Babel。 It gives you some really cool stuff. 它给您一些非常酷的东西。

There are 2 problems with using window object: 使用window对象存在两个问题:

  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 考虑一下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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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