How to get length string json in js or jQuery - javascript

i have this code,
buildSelect: function (data) {
var response = $.parseJSON(data);
alert(response.length);
var s = "<select>";
if (response && response.length) {
for (var i = 0, l = response.length; i < l; i++) {
var ri = response[i];
s += '<option value="' + ri.CUSTOMS_ID + '">'
+ ri.CUSTOMS_NAME + '</option>';
}
}
return s + "</select>";
}
},
i want check response is n't null or empty and get length i write this code response.length
but return undifine
and data return
{"rows":[{"id":1,"cell":["1","بندرامام خميني","IMAM KHOMEINI PORT","True",null]},{"id":2,"cell":["2","آبادان","ABADAN","True",null]},{"id":3,"cell":["3","خرمشهر","KHORRAMSHAHR","True",null]},{"id":4,"cell":["4","بندرعباس","BANDAR ABBAS","True",null]},{"id":5,"cell":["5","بوشهر","BUSHEHR","True",null]},{"id":6,"cell":["6","تهران","TEHRAN","True",null]},{"id":7,"cell":["7","شيراز","SHIRAZ","True",null]},{"id":8,"cell":["8","دبي","DUBAI","True",null]}],"Page":0,"Total":0,"Records":0}
i want if Rows isn't empty all child add to DropDownlist
plese help me, thanks

The issue is that response doesn't have a length property. However, response.rows, as an Array, does:
var response = $.parseJSON(data);
alert(response.rows.length);
You could then save a reference to response.rows and use that going forward:
var rows = response.rows;
alert(rows.length);
var s = "<select>";
if (rows && rows.length) {
for (var i = 0, l = rows.length; i < l; i++) {
var ri = rows[i];
s += '<option value="' + ri.id + '">' + ri.cell[1] + '</option>';
}
}
return s + "</select>";

$.parseJSON(data) returns JavaScript object and not a string. You cannot use length on an object. According to documentation $.parseJSON will return null if you pass in nothing, an empty string, null, or undefined.
UPD:
In your particular case it is enough to check that response is not null (no need to check the length). If data is not a valid JSON then $.parseJSON(data) will through an exception. You may want to catch it as well.

Once you've parsed the JSON string, in this case, you will get an Object in you var response. JavaScript objects do not have a length property. If you just want to check for a null or empty value then do one or more of the following.
var data = "";//in case of null data
if(!data){
//do something
}
//or
if(data === ''){
//do something
}
Now, if you want to check whether your rows are empty,
var data = {
rows:{}
};//assuming an empty rows object
if($.isEmptyObject(data.rows)){
//do something
}

Since object does not contain length property/method and there is no sense for length of object.you can assign methods and properties to each object, pre-written or self-defined.
In your case try to search for object data/properties,like
for(keys in response){
check some properties related on keys
}

Related

chosen-select mutliple select update from an array

I'm using the chosen plugin for a multiple select. I want to retrieve the customer pre-selected values from the database and display them in the multiple select when i return the rest of the data.
The following code works fine:
$('.chosen-select').val(["Test1", "Test2"]).trigger('chosen:updated');
However when I try and put a variable in there like below, it doesn't populate the values.
$('.chosen-select').val([res]).trigger('chosen:updated');
I've pulled the data out and I then loop through the array and store it in a variable. I've checked the contents of the res variable and it's correct, so now I'd like to reference it within the square brackets but it doesn't work, and it doesn't throw any errors. Any help would be much appreciated!
var i;
var res = "";
for (i = 0; i < array.length; i++) {
array[i] = $.trim(array[i]);
var buildValue2 = '"' + array[i] + '", ';
if (i == array.length - 1) {
/* this is the last one so no comma*/
buildValue2 = '"' + array[i] + '"';
}
res = res.concat(buildValue2);
}
alert(res);
$('.chosen-select').val([res]).trigger('chosen:updated');

How to prepare data string but the string does not end with null

I want to make dataSet like (11,22) , (11,22,33) , (11,22,33,44) , (11,null,33,44),(11,null,null,44),(11,null,33)
but it should not end with null.
(means the dataSet string should not come (11,22,null,null) like this ).
hpVal=11, outputRpmVal=22,ratioVal=33,outputSpeedVal=44
Assume the above values will come to the arrayPrepareFunction. Anybody could you please help me to make the dataSet string like the above mentioned format?
while making the array set it should not use else if.
The dynamic data will come from user side. i will attach the screen shot. according to the user selection value will be change.
this is the select box order hpVal, outputRpmVal, ratioVal, outputSpeedVal.
For example: if user selects:
(hpVal=11, outputRpmVal=null,ratioVal=33)
the dataset should be like this (11,null,33).
if user selects:
(hpVal=11, outputRpmVal=null,ratioVal=null,outputSpeedVal=44)
the dataset should be like this (11,null,null,44).
if user selects:
(hpVal=11, outputRpmVal=22,ratioVal=null,outputSpeedVal=null)
the dataset should be like this (11,22).
var dataSet,avoid=",null";
function arrayPrepareFunction(hpVal,outputRpmVal,ratioVal,outputSpeedVal){
dataSet="("+hpVal+","+outputRpmVal+","+ratioVal+","+outputSpeedVal+")";
dataSet = dataSet.replace(avoid,'');
if(dataSet.indexOf(avoid) != -1){
dataSet = dataSet.replace(avoid,'');
}
console.log(dataSet);
}
arrayPrepareFunction(11,null,33)
arrayPrepareFunction(11,null,null,44)
arrayPrepareFunction(11,22,null,null)
If you want to construct a string from all the passed arguments and avoid having nullin the last of the string, the best solution would be to treat the inputs as an array, make your check for null items then transform this array into a string.
This is how should be your code:
function arrayPrepareFunction(hpVal, outputRpmVal, ratioVal, outputSpeedVal) {
dataSet = Object.values(arguments);
var i = dataSet.length;
while (dataSet[i - 1] == null && i > 0) {
dataSet.pop();
i--;
}
dataSet = "(" + dataSet.map(a => a == null ? "" + a : a).join(", ") + ")";
console.log(dataSet);
}
It uses Object.values(arguments) to get the input arguments
as array.
Keeps removing last item from the array if it is null.
Then transform this array into a string.
Demo:
var dataSet, avoid = ",null";
function arrayPrepareFunction(hpVal, outputRpmVal, ratioVal, outputSpeedVal) {
dataSet = Object.values(arguments);
var i = dataSet.length;
while (dataSet[i - 1] == null && i > 0) {
dataSet.pop();
i--;
}
dataSet = "(" + dataSet.map(a => a == null ? "" + a : a).join(", ") + ")";
console.log(dataSet);
}
arrayPrepareFunction(11, null, 33)
arrayPrepareFunction(11, null, null, 44)
arrayPrepareFunction(11, 22, null, null)
Not sure if this is the best answer, but it seams to work:
This puts all the elements into an array >> removes the last few elements if null >> format
function arrayPrepareFunction(hpVal,outputRpmVal,ratioVal,outputSpeedVal){
let arr = [hpVal, outputRpmVal, ratioVal, outputSpeedVal];
for(let i = arr.length-1; i >= 0; i --){
if(arr[i] == null) {
arr.pop();
}
else {
break;
}
}
let dataSet = '('
for(let i = 0; i < arr.length; i ++) {
dataSet += arr[i] + (i != arr.length - 1? ',': '');
}
dataSet += ')';
console.log(dataSet);
}
arrayPrepareFunction(11,null,33);
arrayPrepareFunction(11,null,null,44);
arrayPrepareFunction(11,22,null,null);
Outputs:
(11,null,33)
(11,null,null,44)
(11,22)
My suggestion is a different approach:
First create an array with the values, it's better to work than a string with all values concated.
Then be sure that you are using a string "null" not the value null, it will help in your case. (Did that with .map())
After that, loop through the array from back to end, checking for "null", if you find one, then splice/delete it from array, if the value is not null, then stop the loop because it is a valid value.
To finish, just join the array with , and you will have what you need.
var dataSet;
function arrayPrepareFunction(hpVal,outputRpmVal,ratioVal,outputSpeedVal){
dataArray=[hpVal,outputRpmVal,ratioVal,outputSpeedVal];
dataArray = dataArray.map(function(x){
if (x == null || typeof x == 'undefined'){
return "null";
}else{
return x;
}
});
for (var i = dataArray.length-1; i >= 0; i--){
var value = dataArray[i];
if (value == "null"){
dataArray.splice(i,1);
}else{
break;
}
}
var dataSet = "(" + dataArray.join(",") + ")"
console.log(dataSet);
}
arrayPrepareFunction(11,null,33)
arrayPrepareFunction(11,null,null,44)
arrayPrepareFunction(11,22,null,null)

Pull information from a data file?

I have over 170000 entries of data in data file in this format:
1479661:-1,1,-1,-898,-769,0.00;-1,2,-1,-96,-1402,0.00;-1,3,-1,117,-1397,0.00;-1,4,-1,-4,-2420,0.00;4,5,-1,5570,4395,0.00;4,6,-1,5570,4395,0.00;4,7,-1,5570,4395,0.00;4,8,-1,5570,4395,0.00;4,9,-1,5570,4395,0.00;4,10,-1,5570,4395,0.00;4,11,-1,5570,4395,0.00;4,12,-1,5570,4395,0.00;4,13,-1,5570,4395,0.00;4,14,-1,5570,4395,0.00;-1,15,-1,913,-3533,0.00;4,16,-1,5570,4395,0.00;4,17,-1,5570,4395,0.00;4,18,-1,5570,4395,0.00;4,19,-1,5570,4395,0.00;4,20,-1,5570,4395,0.00;4,21,-1,5570,4395,0.00;4,22,-1,5570,4395,0.00;4,23,-1,5570,4395,0.00;4,24,-1,5570,4395,0.00;4,25,-1,5570,4395,0.00;4,26,-1,5570,4395,0.00;4,27,-1,5570,4395,0.00;4,28,-1,5570,4395,0.00;4,29,-1,5570,4395,0.00;:117,-1397,7,7.00,A,Dead;:
1479662:-1,1,-1,-898,-769,0.00;-1,2,-1,-96,-1402,0.00;-1,3,-1,117,-1392,0.00;-1,4,-1,-6,-2419,0.00;4,5,-1,5570,4395,0.00;4,6,-1,5570,4395,0.00;4,7,-1,5570,4395,0.00;4,8,-1,5570,4395,0.00;4,9,-1,5570,4395,0.00;4,10,-1,5570,4395,0.00;4,11,-1,5570,4395,0.00;4,12,-1,5570,4395,0.00;4,13,-1,5570,4395,0.00;4,14,-1,5570,4395,0.00;-1,15,-1,913,-3533,0.00;4,16,-1,5570,4395,0.00;4,17,-1,5570,4395,0.00;4,18,-1,5570,4395,0.00;4,19,-1,5570,4395,0.00;4,20,-1,5570,4395,0.00;4,21,-1,5570,4395,0.00;4,22,-1,5570,4395,0.00;4,23,-1,5570,4395,0.00;4,24,-1,5570,4395,0.00;4,25,-1,5570,4395,0.00;4,26,-1,5570,4395,0.00;4,27,-1,5570,4395,0.00;4,28,-1,5570,4395,0.00;4,29,-1,5570,4395,0.00;:117,-1392,7,7.07,A,Dead;:
Now each data array starts with a unique id and i was wondering is there a convenient way to push each entry 1479661 then 1479662 every second to an array and assign the values within the unique id into 6 fields that update.
Now I ask if there is a more convenient way as currently I am using this method:
Data comprises of three chunks in a single line
Split the link into chunks
var chunkOne = [1479661];
var chunkTwo = [-1,1,-1,-898,-769,0.00,-1,2,-1,-96,-1402,0.00,-1,3,-1,117,-1397,0.00,-1,4,-1,-4,-2420,0.00,4,5,-1,5570,4395,0.00,4,6,-1,5570,4395,0.00,4,7,-1,5570,4395,0.00,4,8,-1,5570,4395,0.00,4,9,-1,5570,4395,0.00,4,10,-1,5570,4395,0.00,4,11,-1,5570,4395,0.00,4,12,-1,5570,4395,0.00,4,13,-1,5570,4395,0.00,4,14,-1,5570,4395,0.00,-1,15,-1,913,-3533,0.00,4,16,-1,5570,4395,0.00,4,17,-1,5570,4395,0.00,4,18,-1,5570,4395,0.00,4,19,-1,5570,4395,0.00,4,20,-1,5570,4395,0.00,4,21,-1,5570,4395,0.00,4,22,-1,5570,4395,0.00,4,23,-1,5570,4395,0.00,4,24,-1,5570,4395,0.00,4,25,-1,5570,4395,0.00,4,26,-1,5570,4395,0.00,4,27,-1,5570,4395,0.00,4,28,-1,5570,4395,0.00,4,29,-1,5570,4395,0.00];
var chunkThree = [117,-1397,7,7.00,"A","Dead"];
Then get length of each array:
var chunkOneLength = chunkOne.length;
var chunkTwoLength = chunkTwo.length;
var chunkThreeLength = chunkThree.length;
Pick out the nth value in the array depending on the data chunk:
//uniqueID set as first
for (var i = 0; i < chunkOneLength; i = i + 1) {
// useful code would go here
alert("This is the unique ID " + chunkOne[i]);
}
//teamval
for (var i = 0; i < chunkTwoLength; i = i + 6) {
// useful code would go here
alert("This is the teamVal " + chunkTwo[i]);
}
Now the only problem I see with this method, is that the original data array will need to be formatted and separated into chunks every time.
As you have a separator on each section i.e. : you can actually use split to split them up like below and push them into a array and only have to do 2 loops - firstly pushing the split data in a new array and then looping through them and populating the structure.
Please note as long as each chunk of data is separated with : this will work with anything even if you expand the data later. obviously it will not work if you remove the : separator.
example below:
var splitChucks = [];
var chucks = [ "1479661:-1,1,-1,-898,-769,0.00;-1,2,-1,-96,-1402,0.00;-1,3,-1,117,-1397,0.00;-1,4,-1,-4,-2420,0.00;4,5,-1,5570,4395,0.00;4,6,-1,5570,4395,0.00;4,7,-1,5570,4395,0.00;4,8,-1,5570,4395,0.00;4,9,-1,5570,4395,0.00;4,10,-1,5570,4395,0.00;4,11,-1,5570,4395,0.00;4,12,-1,5570,4395,0.00;4,13,-1,5570,4395,0.00;4,14,-1,5570,4395,0.00;-1,15,-1,913,-3533,0.00;4,16,-1,5570,4395,0.00;4,17,-1,5570,4395,0.00;4,18,-1,5570,4395,0.00;4,19,-1,5570,4395,0.00;4,20,-1,5570,4395,0.00;4,21,-1,5570,4395,0.00;4,22,-1,5570,4395,0.00;4,23,-1,5570,4395,0.00;4,24,-1,5570,4395,0.00;4,25,-1,5570,4395,0.00;4,26,-1,5570,4395,0.00;4,27,-1,5570,4395,0.00;4,28,-1,5570,4395,0.00;4,29,-1,5570,4395,0.00;:117,-1397,7,7.00,A,Dead;:", "1479662:-1,1,-1,-898,-769,0.00;-1,2,-1,-96,-1402,0.00;-1,3,-1,117,-1392,0.00;-1,4,-1,-6,-2419,0.00;4,5,-1,5570,4395,0.00;4,6,-1,5570,4395,0.00;4,7,-1,5570,4395,0.00;4,8,-1,5570,4395,0.00;4,9,-1,5570,4395,0.00;4,10,-1,5570,4395,0.00;4,11,-1,5570,4395,0.00;4,12,-1,5570,4395,0.00;4,13,-1,5570,4395,0.00;4,14,-1,5570,4395,0.00;-1,15,-1,913,-3533,0.00;4,16,-1,5570,4395,0.00;4,17,-1,5570,4395,0.00;4,18,-1,5570,4395,0.00;4,19,-1,5570,4395,0.00;4,20,-1,5570,4395,0.00;4,21,-1,5570,4395,0.00;4,22,-1,5570,4395,0.00;4,23,-1,5570,4395,0.00;4,24,-1,5570,4395,0.00;4,25,-1,5570,4395,0.00;4,26,-1,5570,4395,0.00;4,27,-1,5570,4395,0.00;4,28,-1,5570,4395,0.00;4,29,-1,5570,4395,0.00;:117,-1392,7,7.07,A,Dead;:"];
for (var i = 0; i < chucks.length; i++){
splitChucks.push(chucks[i].split(':'))
}
for (var h = 0; h < splitChucks.length; h++) {
alert("This is the unique ID " + splitChucks[h][0]);
alert("This is the teamVal " + splitChucks[h][1]);
}
Hope this helps, this is a much more efficient way to do your task :)
var splitChucks = [];
var chucks = [ "1479661:-1,1,-1,-898,-769,0.00;-1,2,-1,-96,-1402,0.00;-1,3,-1,117,-1397,0.00;-1,4,-1,-4,-2420,0.00;4,5,-1,5570,4395,0.00;4,6,-1,5570,4395,0.00;4,7,-1,5570,4395,0.00;4,8,-1,5570,4395,0.00;4,9,-1,5570,4395,0.00;4,10,-1,5570,4395,0.00;4,11,-1,5570,4395,0.00;4,12,-1,5570,4395,0.00;4,13,-1,5570,4395,0.00;4,14,-1,5570,4395,0.00;-1,15,-1,913,-3533,0.00;4,16,-1,5570,4395,0.00;4,17,-1,5570,4395,0.00;4,18,-1,5570,4395,0.00;4,19,-1,5570,4395,0.00;4,20,-1,5570,4395,0.00;4,21,-1,5570,4395,0.00;4,22,-1,5570,4395,0.00;4,23,-1,5570,4395,0.00;4,24,-1,5570,4395,0.00;4,25,-1,5570,4395,0.00;4,26,-1,5570,4395,0.00;4,27,-1,5570,4395,0.00;4,28,-1,5570,4395,0.00;4,29,-1,5570,4395,0.00;:117,-1397,7,7.00,A,Dead;:", "1479662:-1,1,-1,-898,-769,0.00;-1,2,-1,-96,-1402,0.00;-1,3,-1,117,-1392,0.00;-1,4,-1,-6,-2419,0.00;4,5,-1,5570,4395,0.00;4,6,-1,5570,4395,0.00;4,7,-1,5570,4395,0.00;4,8,-1,5570,4395,0.00;4,9,-1,5570,4395,0.00;4,10,-1,5570,4395,0.00;4,11,-1,5570,4395,0.00;4,12,-1,5570,4395,0.00;4,13,-1,5570,4395,0.00;4,14,-1,5570,4395,0.00;-1,15,-1,913,-3533,0.00;4,16,-1,5570,4395,0.00;4,17,-1,5570,4395,0.00;4,18,-1,5570,4395,0.00;4,19,-1,5570,4395,0.00;4,20,-1,5570,4395,0.00;4,21,-1,5570,4395,0.00;4,22,-1,5570,4395,0.00;4,23,-1,5570,4395,0.00;4,24,-1,5570,4395,0.00;4,25,-1,5570,4395,0.00;4,26,-1,5570,4395,0.00;4,27,-1,5570,4395,0.00;4,28,-1,5570,4395,0.00;4,29,-1,5570,4395,0.00;:117,-1392,7,7.07,A,Dead;:"];
for (var i = 0; i < chucks.length; i++){
splitChucks.push(chucks[i].split(':'))
}
for (var h = 0; h < splitChucks.length; h++) {
alert("This is the unique ID " + splitChucks[h][0]);
alert("This is the teamVal " + splitChucks[h][1]);
}
One of the best purposes of an unique ID is to act as an index. So, instead of iterating over your index array (chunkOne), use ID as an Object key!
// 1479661:-1,1,-1,-898,-769,0.00;-1,2,-1,-96,-1402,0.00;-1,3,-1,117,-1397,0.00;-1,4,-1,-4,-2420,0.00;4,5,-1,5570,4395,0.00;4,6,-1,5570,4395,0.00;4,7,-1,5570,4395,0.00;4,8,-1,5570,4395,0.00;4,9,-1,5570,4395,0.00;4,10,-1,5570,4395,0.00;4,11,-1,5570,4395,0.00;4,12,-1,5570,4395,0.00;4,13,-1,5570,4395,0.00;4,14,-1,5570,4395,0.00;-1,15,-1,913,-3533,0.00;4,16,-1,5570,4395,0.00;4,17,-1,5570,4395,0.00;4,18,-1,5570,4395,0.00;4,19,-1,5570,4395,0.00;4,20,-1,5570,4395,0.00;4,21,-1,5570,4395,0.00;4,22,-1,5570,4395,0.00;4,23,-1,5570,4395,0.00;4,24,-1,5570,4395,0.00;4,25,-1,5570,4395,0.00;4,26,-1,5570,4395,0.00;4,27,-1,5570,4395,0.00;4,28,-1,5570,4395,0.00;4,29,-1,5570,4395,0.00;:117,-1397,7,7.00,A,Dead;:
var data =
{
1479661:
[
-1,1,-1,-898,-769,0.00,-1,2,-1,-96,-1402,0.00,-1,3,-1,117,-1397,0.00,-1,4,-1,-4,-2420,0.00,4,5,-1,5570,4395,0.00,4,6,-1,5570,4395,0.00,4,7,-1,5570,4395,0.00,4,8,-1,5570,4395,0.00,4,9,-1,5570,4395,0.00,4,10,-1,5570,4395,0.00,4,11,-1,5570,4395,0.00,4,12,-1,5570,4395,0.00,4,13,-1,5570,4395,0.00,4,14,-1,5570,4395,0.00,-1,15,-1,913,-3533,0.00,4,16,-1,5570,4395,0.00,4,17,-1,5570,4395,0.00,4,18,-1,5570,4395,0.00,4,19,-1,5570,4395,0.00,4,20,-1,5570,4395,0.00,4,21,-1,5570,4395,0.00,4,22,-1,5570,4395,0.00,4,23,-1,5570,4395,0.00,4,24,-1,5570,4395,0.00,4,25,-1,5570,4395,0.00,4,26,-1,5570,4395,0.00,4,27,-1,5570,4395,0.00,4,28,-1,5570,4395,0.00,4,29,-1,5570,4395,0.00,117,-1397,7,7.00,"A","Dead"
]
// More data...
};
Object.keys(data).forEach(function(key)
{
console.log('This is ID ' + key);
data[key].forEach(function(value,index,array)
{
console.log('Index ' + index + ' of data key ' + key + ':');
console.log(data[key][index]);
});
});
Test this on any modern browser's console or node.js instance to see results.

Find the next key id in object

I stored an object in one variable (Consider as datatable).
var data=[{"controlID":"A","currentValue":"10","onChange":"","onClick":""},
{"controlID":"B","currentValue":"5","onChange":"Testing(A,B)","onClick":""},
{"controlID":"C","currentValue":"-5","onChange":"Testing1(A,B)","onClick":""},
{"controlID":"D","currentValue":"","onChange":"Testing2(B,C)","onClick":""},{"controlID":"E","currentValue":"","onChange":"Testing3(C,D)","onClick":""},{"controlID":"F","currentValue":"","onChange":"","onClick":""}];
Now I know the second row key value as B. How to I Get the Third row (i.e., "C" row values)
Am new of this field. Please help us to helpful.
This function will return your index:
var FindIndexOfControlID = function(id, data){
for(var i = 0; i < data.length ; i++){
if( data[i]['controlID'] == id ){
return i;
}
}
};
Usage:
var index = FindIndexOfControlID('C', data);
Live Example
http://jsfiddle.net/urahara/medhgm7b/
NOTE
Alternatively you may also want to implement function that returns index of any specified property and value:
var FindIndexOfProperty = function(value, property, data){
for(var i = 0; i < data.length ; i++){
if( data[i][property] == value ){
return i;
}
}
};
Usage
FindIndexOfProperty('-5', 'currentValue',data); // returns 2
You can return the third row in javascript by simply executing var thirdRow = data[2]. The row will be returned as an object.

How to create json by JavaScript for loop?

I have array of select tag.
<select id='uniqueID' name="status">
<option value="1">Present</option>
<option value="2">Absent</option>
</select>
and I want to create a json object having two fields 'uniqueIDofSelect and optionValue' in JavaScript.
I use getElementsByName("status") and I iterate on it.
EDIT
I need out put like
[{"selectID":2,"OptionValue":"2"},
{"selectID":4,"optionvalue":"1"}]
and so on...
From what I understand of your request, this should work:
<script>
// var status = document.getElementsByID("uniqueID"); // this works too
var status = document.getElementsByName("status")[0];
var jsonArr = [];
for (var i = 0; i < status.options.length; i++) {
jsonArr.push({
id: status.options[i].text,
optionValue: status.options[i].value
});
}
</script>
var sels = //Here is your array of SELECTs
var json = { };
for(var i = 0, l = sels.length; i < l; i++) {
json[sels[i].id] = sels[i].value;
}
If you want a single JavaScript object such as the following:
{ uniqueIDofSelect: "uniqueID", optionValue: "2" }
(where option 2, "Absent", is the current selection)
then the following code should produce it:
var jsObj = null;
var status = document.getElementsByName("status")[0];
for (i = 0, i < status.options.length, ++i) {
if (options[i].selected ) {
jsObj = { uniqueIDofSelect: status.id, optionValue: options[i].value };
break;
}
}
If you want an array of all such objects (not just the selected one), use michael's code but swap out status.options[i].text for status.id.
If you want a string that contains a JSON representation of the selected object, use this instead:
var jsonStr = "";
var status = document.getElementsByName("status")[0];
for (i = 0, i < status.options.length, ++i) {
if (options[i].selected ) {
jsonStr = '{ '
+ '"uniqueIDofSelect" : '
+ '"' + status.id + '"'
+ ", "
+ '"optionValue" : '
+ '"'+ options[i].value + '"'
+ ' }';
break;
}
}
If I want to create JavaScript Object from string generated by for loop then I would JSON to Object approach. I would generate JSON string by iterating for loop and then use any popular JavaScript Framework to evaluate JSON to Object.
I have used Prototype JavaScript Framework. I have two array with keys and values. I iterate through for loop and generate valid JSON string. I use evalJSON() function to convert JSON string to JavaScript object.
Here is example code. Tryout on your FireBug Console
var key = ["color", "size", "fabric"];
var value = ["Black", "XL", "Cotton"];
var json = "{ ";
for(var i = 0; i < key.length; i++) {
(i + 1) == key.length ? json += "\"" + key[i] + "\" : \"" + value[i] + "\"" : json += "\"" + key[i] + "\" : \"" + value[i] + "\",";
}
json += " }";
var obj = json.evalJSON(true);
console.log(obj);
Your question is pretty hard to decode, but I'll try taking a stab at it.
You say:
I want to create a json object having two fields
uniqueIDofSelect and optionValue in javascript.
And then you say:
I need output like
[{"selectID":2,"optionValue":"2"},
{"selectID":4,"optionvalue":"1"}]
Well, this example output doesn't have the field named uniqueIDofSelect, it only has optionValue.
Anyway, you are asking for array of objects...
Then in the comment to michaels answer you say:
It creates json object array. but I need only one json object.
So you don't want an array of objects?
What do you want then?
Please make up your mind.

Categories