Convert { Key : Value } Object Into Standard Variables with jQuery
I give you what I want in PHP :
foreach($my开发者_JS百科array as $key=>$value) { ${$key} = $value; }
Now, can we do it with JS/jQuery ?
This is the jQuery input, I want the classTD value as key, in other words the equivalent of the famous PHP statement ${$key} in the example above:
data = {};
$('#resul_rech_doc_fact tr.document-2 td').each(function(index) {
var classTD = $(this).attr('class');
var contentTD = $(this).text();
data = $.extend(data , { classTD : contentTD });
});
The line:
data = $.extend(data , { classTD : contentTD });
Doesn't do what you expect. It is identical to:
data = $.extend(data , { 'classTD' : contentTD });
It seems you want to evaluate classTD
and sue it as the object's key. You have two options:
You can assign the data
member, modifying data
:
data[classTD] = contentTD;
or you can use $.extend
with a temporary object:
var obj = { };
obj[classTD] = contentTD;
data = $.extend(data, obj);
If you want to convert PHP array to object in Javascript - you can use function :
http://php.net/manual/en/function.json-encode.php
Example from manual:
// PHP
$arr = array ('a'=>1,'b'=>2,'c'=>3,'d'=>4,'e'=>5);
$js = json_encode($arr);
echo $js;
// output
{"a":1,"b":2,"c":3,"d":4,"e":5}
So you can use PHP to "echo" $js
variable to initialize your javascript for example.
For iteration through properties of JS object you can use:
http://www.w3schools.com/js/js_loop_for_in.asp
Example:
for (key in objectInstance)
{
alert(objectInstance[key]); // value
}
I think what you want is:
data = {};
$('#resul_rech_doc_fact tr.document-2 td').each(function(index) {
data[$(this).attr('class')] = $(this).text();
});
If you want to create global variables, you can set poperties on the window
object (but I wouldn't recommend it):
$('#resul_rech_doc_fact tr.document-2 td').each(function(index) {
window[$(this).attr('class')] = $(this).text();
});
Then, if for example you had a class called 'foo' you could access 'foo' as a "global variable". The danger here is that you could very easily overwrite important properties of the window object.
For all web purposes, global scope = window, so:
window['foobar'] = 'bar';
alert(foobar);
Hence the (unrecommendable):
var json = {'foobar':'bar'};
for i in json {
window[i] = json[i];
}
alert(foobar);
Well, you could use with
, but with
is considered harmful:
var obj = { bar: 'foo' };
with (obj) {
alert(bar); // 'foo'
}
alert(bar); // undefined
If you must have the loop, you can do this:
var obj = { bar: 'foo' };
var key, value;
with (obj) {
for (key in obj) {
if (!obj.hasOwnProperty(key)) { // Never forget this check!
continue;
}
value = obj[key];
// Rest of loop here.
}
}
精彩评论