Menu
Hi All
Lets assume the following object
[CODE]
var x = {
y: {
z: 10
}
} ;
Next, I need to retrieve the value ’10’, but the only thing I have is one string as a key
For example (this doesn’t work):
[CODE]
var str = ‘[y][z]’ ; // or ‘y.z’??
alert(x[str]) ; // should alert 10
Can this be done using a single string as input for x ?
cheers
UPDATE: a solution which comes close to what I was looking for is
[CODE]
var str = “x[‘y’][‘z’]” ;
alert(eval(str));
<i>
</i><!DOC HTML>
<html>
<head>
<title> Untitled </title>
<script type="text/javascript">
var x = {
y: {
z: 10
}
};
alert(x.y.z);
</script>
</head>
<body>
</body>
</html>
[CODE]
var str = 'y.z' ;
var items = 'y.z'.split() ;
alert( x[items[0]][items[1]] ;
[/CODE]
var x = {y:{z:10}};
var a = "y.z";
a = a.split(".");
var r = x;
for (var i = 0; i < a.length; i++) {
r = r[a[i]];
}
Well, you could eval it, but I wouldn't recommend that if the user is providing it, so instead, I'd parse the string, splitting it at ".", and then finding the corresponding element.
Something like:[/QUOTE]
var x = {y:{z:10}};
var a = "y.z";
a = a.split(".");
var r = x;
for (var i = 0; i < a.length; i++) {
r = r[a[i]];
}
<i>
</i><script type="text/javascript">
var x = {y:{z:10}};
var a = "y.z";
a = a.split(".");
alert(x[a[0]][a[1]]+' is same as '+x.y.z);
</script>
Why would you need a loop when you already have been told there is 'y.x'?[/QUOTE]
exactly, suppose you don't know anything about the structure of [B]x[/B] and someone (or a webservice) tells to get a value out of the variable and the path is 'm.n.o.p'[/QUOTE]
[CODE]var str = '["y"]["z"]',
x = {
y : {
z : 10
}
};
alert(eval('x' + str)) ; // should alert 10[/CODE]
[CODE]var str = '.' + 'y.z', //notice I add a leading dot
x = {
y : {
z : 10
}
};
alert(eval('x' + str)) ; // should alert 10[/CODE]
I'm questioning why you would need to split the 'm.n.o.p' into an array
when you could use the arrayX.m.n.o.p access directly. ?[/QUOTE]
[CODE]var x = {y:{z:10}};
var a = "y.z";
a.split(".").map(function(a){
return this[0]=this[0][a];
}, [x]).slice(-1)[0];
[/CODE]
[CODE]var x = {y:{z:10}};
var a = "y.z";
a.split(".").map(function(a){
return this[0]=this[0][a];
}, [x]).slice(-1)[0];
[/CODE]
[/QUOTE]
[CODE]var x = {y:{z:10}};
var a = "y.z";
a.split(".").map(function(a){
return this[0]=this[0][a];
}, [x]).slice(-1)[0];
[/CODE]
[/QUOTE]
[CODE]
var x = {y:{z:10}};
var a = "y.z";
console.log( a.split(".")
.map(function(a)
{
console.dir(this) ;
return this[0]=this[0][a];
}, [x])
.slice(-1)[0]) ;
[/CODE]
[CODE]var x = {y:{z:10}};
var a = "y.z";
a.split(".").map(function(a){
return this[0]=this[0][a];
}, [x]).slice(-1)[0];[/CODE]
[CODE]var x = {y:{z:10}};
var a = "y.z";
[/CODE]
[CODE]a.split(".")[/CODE]
[CODE].map( fn, that)[/CODE]
[CODE]}, [x])[/CODE]
This part is admittedly the most confusing aspect. [CODE]return this[0]=this[0][a];[/CODE]
[CODE]x=x[a];
return x;
[/CODE]
i forget not everyone use map(). i don't know why they don't; it makes js so much easier, but alas, they don't...
so, let's walk through the code and inspect what's going on here.
.....
i realize this is over-kill depth-wise, but i wanted to make sure i didn't leave out any details that might be needed.
let me know if any part is unclear, and i'll elaborate.[/QUOTE]
i forget not everyone use map(). i don't know why they don't; it makes js so much easier, but alas, they don't...[/quote]
if (!Array.prototype.map)
{
Array.prototype.map = function(fun /*, thisp */)
{
"use strict";
if (this === void 0 || this === null){
throw new TypeError();
}
var t = Object(this);
var len = t.length >>> 0;
if (typeof fun !== "function"){
throw new TypeError();
}
var res = new Array(len);
var thisp = arguments[1];
for (var i = 0; i < len; i++)
{
if (i in t){
res[i] = fun.call(thisp, t[i], i, t);
}
}
return res;
};
}
but absolutely not readable[/quote]
var x = {y:{z:10}};
var a = "y.z";
var n = a.split(".").map(
function(a) {
return this[0] = this[0][a];
},
[x]
).slice(-1)[0];
//n defined in 106 chars
alert(n);
var i,
n = x,
aa = a.split('.');
for (i = 0; i < aa.length; i++) {
n = n[aa[i]];
}
//n defined in 89 chars
alert(n);
var n=a.split(".").map(function(a){return this[0]=this[0][a];},[x]).slice(-1)[0];
alert(n);
var i,n=x,aa=a.split('.');for(i=0;i<aa.length;i++){n=n[aa[i]];}
alert(n);
a straight forward loop is more readable and less code overall required in the majority of cases.
...
Even compressed the second version wins in the compactness department:
...
Don't get me wrong, me loves functions and anonymous functions, they have many excellent uses, but I personally don't find .map desirable for the above reasons. To me it only SEEMS like a cool trick to use .map[/QUOTE]
[CODE]eval(function (s,r){var a,x,i=0,m=r.length,q=/([.*+?^${}()|[]/\])/g;for(;i<m;i++){a=r[i]||"";x=RegExp(a.slice(0,1).replace(q,"\$1"),"g");s=s.replace(x,a.slice(1))}return s}("(&n(#var o=Array.prototype,H,i,e={map/i=0,r=[]BVr[i]8G,V}Nr9J<[email protected](G,V#r[g++Kt[i]MNr9every/i=0;[email protected]==m9some/i=1;Q(;mT;#[email protected](tDmCm,V@!Ti#$!0}}$!19lastIndexOf/i=b6-1;Q(;m>i;mT#P@t[mK==a#Nl}}$-194dexOf/i=b60Bt@t[iK==a#Ni}}$-19reduce/i=0,r=b6t[i++]L57r8nul*reduceRight/i=m-1,r=b6t[iT]%>-1;iT#r8nul*QEach:&n(a,b#this.concat().mapU9clean<0,x,O;a=Function(a6Str4g)Bt@(x8G,V)#r[g++KxMNarguments[2]?b:rMQ(H 4 e#i=o[H];o[HKi6e[H]}}());","Vt)U(a,b)
T--BT4
TLB Pif(m 4 t
N$ M}};
</i=0,r=[Cg=L%<
K]=Jfilter
HitGbDiCi
D,t[C],
6||B576
Qfor&functio
@&&9},
8=a.3(7++#
6if(i5m;i
4in3call
#){/:#,
*l,r,t[i],i,t)}$ r},%;for(;i
$return#functio$length
$n(a,b){var t=#=t.#this.concat(),m".split('
')));[/CODE]
[CODE]
var r=[0,1, "2",3,"fred", false, "", NaN, "sally", undefined, "jon"];
r.filter(Boolean)// [1, "2", 3, "fred", "sally", "jon"]
r.map(Number).filter(Number)// [1, 2, 3]
r.map(Number).filter(isFinite)// [0, 1, 2, 3, 0, 0]
r.filter(isNaN).filter(Boolean).map(String)//["fred", "sally", "jon"]
[/CODE]
[CODE]for(var i=0;i<4;i++){
setTimeout(function(){ alert(i);}, i * 2000 )
}[/CODE]
[CODE]
var len = t.length >>> 0;
[/CODE]
0.1.9 — BETA 5.20