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.