I'm trying to create a JSON array dynamically. In the site, there are a dynamic number of <div id="#selected">'s and I need to take all of their values and create a JSON array.
I've come across the .push() functionality, but I have not been able to figure it out.
<!-- there could be a million of these, or only one... each value is unique though -->
<div id="selected" value="5|3"></div>
<div id="selected" value="3|65"></div>
function json_array_selected() {
var JSon = {};
$('div#selected').each(function() {
// let's first split the given values
var Split = $(this).attr('value');
Split = Split.split('|');
var Type = Split[0];
Value = Split[1];
// now let's set up our Json array... using the value = type way, there should never be
// any repeating
JSon.Value = Type;
});
return JSon;
}
Musa
97.9k17 gold badges123 silver badges144 bronze badges
asked Jul 9, 2012 at 22:31
Jacob Kranz
9513 gold badges11 silver badges26 bronze badges
2 Answers 2
instead of
JSon.Value = Type;
try with
JSon[Value] = Type;
or you will always overwrite a key named "Value"
answered Jul 9, 2012 at 22:32
Fabrizio Calderan
124k26 gold badges172 silver badges183 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
First of all, you cannot have two nodes in HTML with same id. You will have to assign some class for those div tags. For example -
<div class="selected" value="5|3"></div>
<div class="selected" value="3|65"></div>
I tried following piece of code on jsfiddle.net
function json_array_selected() {
var JSon = {};
$('div.selected').each(function() {
// let's first split the given values
var Split = $(this).attr('value');
Split = Split.split('|');
var Type = Split[0];
Value = Split[1];
JSon[Value] = Type;
});
return JSon;
}
var res = json_array_selected();
alert(JSON.stringify(res));
alert(res["3"]);
Resulting JSON array is
{"3":"5","65":"3"}
answered Jul 9, 2012 at 23:01
devang
5,5167 gold badges37 silver badges52 bronze badges
1 Comment
Shane Sepac
How would you write the code if you had multiple identical Value objects and didn't want them to be overwritten? For instance if you have "3|65" and "3|75", you'll overwrite the former.
lang-js
$('div#selected')will only get you one element