There is a method in PHP called extract
which does exactly what I want to do here. Say I have an object that looks like this:
var data = {
name: "Olly"
age: 19
};
I want to run a method like extract(data)
so that I can then access the properties in that object by just using name
and age
, instead of data.name
and data.age
.
I've done a bit of Googling and couldn't find anything.
There is a method in PHP called extract
which does exactly what I want to do here. Say I have an object that looks like this:
var data = {
name: "Olly"
age: 19
};
I want to run a method like extract(data)
so that I can then access the properties in that object by just using name
and age
, instead of data.name
and data.age
.
I've done a bit of Googling and couldn't find anything.
Share Improve this question asked Jan 4, 2012 at 16:30 user1082754user1082754 3- Are you using a minifier or optimizer like Yahoo YUI or Google Closure? – Kris Krause Commented Jan 4, 2012 at 16:33
-
1
I suppose Javascript's
with
statement is more closely similar to PHP'sextract
method. That being said,with
is not very mon and I would not use it unless you truly understand how it works. See developer.mozilla/en/JavaScript/Reference/Statements/with – mjc Commented Jan 4, 2012 at 16:36 - @KrisKrause No, I am not. Why do you ask? – user1082754 Commented Jan 4, 2012 at 16:36
2 Answers
Reset to default 10You can use something like this:
function myTestFunction() {
var data = {
name: "Olly",
age: 19,
};
for (var key in data) {
this[key] = data[key];
}
alert(name +" is "+ age +"!");
}
myTestFunction();
(Try that here: http://jsfiddle/dHDxd/3/)
Or even export them to global namespace, by using window[key] = data[key]
.
In any case, be very very careful with that, since the risk of clobbering the global namespace / override other stuff / etc. is very high.
Update: general-purpose extract()
function extract(data, where) {
for (var key in data) {
where[key] = data[key];
}
}
function runTest() {
var myData = { name: "Olly", age: 19, };
extract(myData, this);
alert(name +" is "+ age +"!");
}
runTest();
Here is more generic/multi-level/recurrent namespace extractor :)
function extract(rootObject, key) {
var parts = key.split('.');
var currentKey = parts.shift();
return parts.length > 0 ? extract(rootObject[currentKey], parts.join('.')) : rootObject[currentKey];
}
var myObject = { a: { b: { c: 7 }}};
console.log(extract(myObject, 'a.b.c'));
console.log(extract(myObject, 'a'));