2

Php extract function

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

Similarly I want to access javascript object keys as variable

var myObject = {a: 'cat', b: 'dog'}
// If console 'a' then it should print Cat

I tried using this and eval but it's working in browser only, how is this possible in NodeJs? eval

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

this

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

NOTE: My object has so many keys and i don't want to destructing the object by typing each key name.

Arjun Singh
  • 302
  • 1
  • 12
  • 1
    Does this answer your question? [How do I destructure all properties into the current scope/closure in ES2015?](https://stackoverflow.com/questions/31907970/how-do-i-destructure-all-properties-into-the-current-scope-closure-in-es2015) – iainn Jan 02 '20 at 14:05
  • 1
    try to use `global` instead of `this` when calling `convertKeyToVariable ` – fedeghe Jan 02 '20 at 14:05
  • @fedeghe thanks it worked after using `global`. I missed this – Arjun Singh Jan 02 '20 at 14:18

2 Answers2

6

started from Your proposal, simply less general, following my own suggestion to use global or this thus works in node and browser

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)
fedeghe
  • 1,243
  • 13
  • 22
2

You could use Destructuring read more

//with object
var {a, b} = {a: 'cat', b: 'dog'};
console.log(a); //cat

//with array
var [a, b] = ['cat', 'dog'];
console.log(a); //cat