PHP `extract` 函数相当于 Nodejs (javascript)?

Arj*_*ngh 2 javascript php arrays node.js

PHP提取函数

<?php
$a = "Original";
$my_array = array("a" => "Cat","b" => "Dog", "c" => "Horse");
extract($my_array);
echo $a; // this will print Cat
?>
Run Code Online (Sandbox Code Playgroud)

同样,我想访问 javascript 对象键作为变量

var myObject = {a: 'cat', b: 'dog'}
// If console 'a' then it should print Cat
Run Code Online (Sandbox Code Playgroud)

我尝试使用thisandeval但它只能在浏览器中工作,这在 NodeJs 中怎么可能? 评估

var k = { a: 'a0', b: 'b0' }
Object.keys(k).forEach((key) => {
  eval(`${key}=k[key]`);
  console.log(a)
});
Run Code Online (Sandbox Code Playgroud)

function convertKeyToVariable(data, where) {
    for (var key in data) {
        where[key] = data[key];
    }
}
var k = { a: 'Cat', b: 'Dog' }
convertKeyToVariable(k, this)
console.log(a) // will print Cat
Run Code Online (Sandbox Code Playgroud)

注意:我的对象有很多键,我不想通过键入每个键名称来破坏该对象。

fed*_*ghe 6

从您的提案开始,只是不太笼统,按照我自己的建议使用globalthis因此在节点和浏览器中工作

function extract(data, where) {
    var g = where || (typeof global !== 'undefined' ? global : this);
    for (var key in data){
      if (data.hasOwnProperty(key)){
          g[key] = data[key];
      }
    }
}
var k = { a: 'Cat', b: 'Dog' }
extract(k)
console.log(a) // will print Cat
console.log(b)
Run Code Online (Sandbox Code Playgroud)