How to serializeObject with nested object in javascript? - javascript

I have
"resource_ratio": [
[
"Barbara",
"Ben",
"Anne",
"John",
"Cindy",
"Nick",
"Lex",
"Edd",
"Eric",
"Jacky",
"Paul"
],
[
0.11974110032362459,
0.037756202804746494,
0.23516720604099245,
0.10895361380798274,
0.10140237324703344,
0.03559870550161812,
0.02912621359223301,
0.08737864077669903,
0.02481121898597627,
0.1186623516720604,
0.10140237324703344
]
]
this 2 dim array that I want to display on HTML page using javascript
and then get the result back in JSON from after clicking a button.
For now, I displayed the values of resource_raio using this
var resourceRatioBoxTag = new Array();
var resourceRatioTag = new Array();
for (var i = 0; i < selectedData.resource_ratio.length; i++) {
//selectedData.resource_ratio[1][0]
resourceRatioBoxTag[i] = "<input id='resourceRatio[" + i + "]' name='resourceRatio'>";
for (var j = 0; j < selectedData.resource_ratio[i].length; j++) {
resourceRatioBoxTag[i] += "<input type='text' id='resourceRatio[" + i + "][" + j + "]' value='" + selectedData.resource_ratio[i][j] + "' name='" + i + "'>";
}
resourceRatioBoxTag[i] += "</input>";
$("#resourceRatioDiv").append(resourceRatioBoxTag[i]);
}
which gave me result of one single array with all the values inside like [val1, val2, val3]
And when I do
var dataBox = $('#inputDataForm').serializeObject();
the JSON result
It's not in form of
"resource_ratio": [
[
"Barbara",
"Ben",
"Anne",
"John",
"Cindy",
"Nick",
"Lex",
"Edd",
"Eric",
"Jacky",
"Paul"
],
[
0.11974110032362459,
0.037756202804746494,
0.23516720604099245,
0.10895361380798274,
0.10140237324703344,
0.03559870550161812,
0.02912621359223301,
0.08737864077669903,
0.02481121898597627,
0.1186623516720604,
0.10140237324703344
]
]
as I wanted it to be. So I've tried changing the name of the input of array values (Since I've learned that SerializeObject group values by the name of input) and made something like this
for (var i = 0; i < selectedData.resource_ratio.length; i++) {
//selectedData.resource_ratio[1][0]
resourceRatioBoxTag[i] = "<p id='resourceRatio[" + i + "]' name='resourceRatio'>";
for (var j = 0; j < selectedData.resource_ratio[i].length; j++) {
resourceRatioBoxTag[i] += "<input type='text' id='resourceRatio[" + i + "][" + j + "]' value='" + selectedData.resource_ratio[i][j] + "' name='" + i + "'>";
}
resourceRatioBoxTag[i] += "</p>";
$("#resourceRatioDiv").append(resourceRatioBoxTag[i]);
}
(Its the same code except I changed the p tag to input tag]
which gave me serialized values of
"0": [
"Barbara",
"Ben",
"Anne",
"John",
"Cindy",
"Nick",
"Lex",
"Edd",
"Eric",
"Jacky",
"Paul"
],
"1": [
"0.11974110032362459",
"0.037756202804746494",
"0.23516720604099245",
"0.10895361380798274",
"0.10140237324703344",
"0.03559870550161812",
"0.02912621359223301",
"0.08737864077669903",
"0.02481121898597627",
"0.1186623516720604",
"0.10140237324703344"
]
which is ALMOST same as how I want it to be, except it's not INSIDE the resource_ratio values, it's grouped by [0] and [1] (following by the input name).
What should I do to get my resourceRatio[i][j] values inside [i] which is inside the resourceRatio key? I'm sorry if my question is so confusing
the serializeObject is a plug in of jquery I used. It's this:
$.fn.serializeObject = function () {
var o = {};
var a = this.serializeArray();
$.each(a, function () {
if (o[this.name]) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
};

The easiest way to convert a value to JSON is to use JSON.stringify:
let dataAsString = JSON.stringify( myObject )
This will break if your object has any circular references. That won't be a problem if your data is a typical piece of business data.
And then to convert it back:
let data = JSON.parse( dataAsString )
Unless you have a very special reason for doing so, I'd recommend that you always use this built-in capability instead of something from a library like jQuery.

Related

How to handle an dynamic array?

I want to show up the names of the members of an array "path" in my console.
console.log("start: ", path[0].name, "second: ", path[1].name, "third: ", path[2]name, ....)
But the problem is, that my array always changes it's size (clicking algorithm), that means sometimes it has the lenght 4 or sometimes 8 ect.
How can i adjust the console.log code to this dynamic array?
Thanks so much!
Try
path.forEach((each, i)=>{
console.log ("item" + i+ ':' + each.name );
})
Something like this:
var path = ['Prit', 'Bab', 'Nav']
var item = ["first","second", "third"];
for (i = 0; i < path.length;i++){
console.log(item[i] + ":" + path[i])
}
Try something like this for single line result set ...
var result = "";
for (var i = 0, len = path.length; i < len; i++) {
if (i !== 0) {
result += ", ";
}
result += (i + 1) + ": " + path[i].name;
}
console.log(result);
you could use a for loop here , ie,
for (var i=0;i<path.length;i++) {
console.log("item no "+ i +": " + path[i]);
}
/* Console Array */
var consoleArray = new Array;
/* Names */
var path = [
{name: 'bob'},
{name: 'jimmy'},
{name: 'chris'},
{name: 'alexander'},
{name: 'mark'}
];
/* Loop */
for(var i = 0; i < path.length; i++) {
consoleArray.push((i + 1) + ': ' + path[i].name);
}
/* Console Log */
console.log(consoleArray.join("\n"));
With ES6, you could use spread syntax ....
var path = [{ name: 'Jo'}, { name: 'John'}, { name: 'Jane'}];
console.log(...path.map((a, i) => (i ? i + 1 : 'Start') + ': ' + a.name));

i want to access all keys and values of this json objects using javascript

<!DOCTYPE html>
<html>
<body>
<p>employees var having the json array n objects</p>
<p id="demo"></p>
<script>
var employees = [{
"_id": "P_00001",
"Product": "SEA EXPORT",
"Status": "Active",
"Origin": "JEBEL ALI(DUBAI), United Arab Emirates (AEJEA)",
"Destination": "CHENNAI, India (INMAA)",
"CreatedDate": "2016-01-13T07:17:05.251Z"
}];
for( i=0 ; i < employees.length ; i++ )
{
document.getElementById("demo").innerHTML +="<br/>" + employees[i]["_id"] + " " + employees[i][key()];
}
</script>
</body>
</html>
json object with keys and values ihave stored in var employees
i dont know how to display the keys and values of the object using forloop
You can use the for/in loop to access all keys in an object, and then use that key to access the value:
var txt = "";
var person = {fname:"John", lname:"Doe", age:25};
var x;
for (x in person) {
txt += person[x] + " ";
}
alert(txt);
http://www.w3schools.com/js/tryit.asp?filename=tryjs_object_for_in
EDIT 1
This function highlights the key and value:
var employees = [{
"_id": "P_00001",
"Product": "SEA EXPORT",
"Status": "Active",
"Origin": "JEBEL ALI(DUBAI), United Arab Emirates (AEJEA)",
"Destination": "CHENNAI, India (INMAA)",
"CreatedDate": "2016-01-13T07:17:05.251Z"
}];
for( var e of employees ) {
for( var key in e ) {
alert('The key "'+ key + '" represents the value "' + e[key] + '"')
}
}
You can :
for(i in employees){
var key = i;
var val = employees[i];
for(j in val){
var sub_key = j;
var sub_val = val[j];
document.getElementById("demo").innerHTML +="<br/>" + (sub_key) + " " + sub_val;
}
}
Fiddle

recursively object to ul list and add class with index in javascript

I have a working recursive function that creates an <ul> list from an object, it works fine,
my problem is that I want to keep track of the index, and add it as class to <li> elements,
I need that the "index count system" will count in a particular way, and this is the output that I want:
class0
class0_0
class0_0_0
class0_0_1
class0_1
class0_1_0
class0_1_1
class1
class1_0
class1_0_0
class1_0_1
class1_1
class1_1_0
class1_1_1
by increasing, restarting and have maybe multiple "index count" variables in the recirsive function
This is what I'm trying, but I still can't figure out where to properly set, increase, reset the counters to achieve that result..
var i = 0;
function object2ul(data) {
var json = "<ul>";
for(var key in data) {
json = json + "<li>" +'<b>'+i+'</b>'+ key; i++;
if(typeof data[key] == 'object') {
json = json + object2ul(data[key]);
}else{ i=0;
json = json + '<ul><li>'+ data[key]+'</li></ul>';
}
json = json + "</li>";
}
return json + "</ul>";
}
document.body.innerHTML = object2ul(object);
In this example I omitted to set the classes avoiding to complicate the function
DEMO
Something like this?
var object = {
root0: {
child0: {
leaf: 'text',
leaf: 'text'
},
child1: {
leaf: 'text',
leaf: 'text'
}
},
root1: {
child0:{
leaf: 'text',
leaf: 'text'
},
child1: {
leaf: 'text',
leaf: 'text'
}
}
};
var i = 0;
function object2ul(data, prefix) {
prefix = prefix || '0'; // default
var json = "<ul>";
var childIndex = 0;
for(var key in data) {
json = json + "<li>" +'<b>'+i+'</b>'+ key; i++;
if(typeof data[key] == 'object') {
json = json + object2ul(data[key], prefix + '_' + childIndex);
}else{ i=0;
json = json + '<ul><li>'+ data[key]+'---(' + prefix + ')</li></ul>';
}
json = json + "</li>";
childIndex++;
}
return json + "</ul>";
}
document.body.innerHTML = object2ul(object);
To get the kind of indexing you want, you are going to have to use Object.keys. The following should work for an arbitrary object:
var testObj = { a: { b: '2', d: '5', e: { f: '3' } }, c: '3' };
var indexes = [];
var object2ul = function (data) {
var keys = Object.keys(data);
var json = "<ul>";
for (var i = 0; i < keys.length; ++i) {
var key = keys[i];
indexes.push(i);
json += "<li>" + "<b>" + indexes.join('_') + "</b>" + key;
if (typeof(data[key]) === 'object') {
json += object2ul(data[key]);
} else {
json += "<ul><li>" + data[key] + "</li></ul>";
}
json += "</li>";
indexes.pop();
}
return json + "</ul>";
}
document.body.innerHTML = object2ul(testObj);
Here's it in action:
JSFiddle

I am trying to fetch objects from a main object

I am trying to fetch objects from a main object. An array in the main object holds
these other objects, I can access the first element by calling 'oData.events.event[0]' but I would like to loop through to get [1], [2], [3] and so on.
//this works
var collection = oData.events.event[0];
$("<li>description: " + collection.description + "</li>").appendTo("#shower");
//this does not work :(
var collection = oData.events.event[0];
var output = "<ul>";
for (var i = 0; i < collection.length; i++)
{
output += "<li>" + collection.description + "</li>";
$(output).appendTo("#shower");
collection = collection + 1 //shift to next array
}
output += "</ul>";
Maybe use a foreach loop
oData.events.event.forEach(function(result) {
console.log(result);
});
Alternatively, try jQuery's .each() function:
$.each(oData.events.event, function(index, value) {
console.log( index + ": " + value );
});
EDIT: It's worth noting that the output of these calls will be an object - you still have to access the data beneath the objects you've looped to!
Fiddle here - however, you can do something like this...
var oData = {
events: {
event: [{ description: '1' },
{ description: '2' },
{ description: '3' }]
}
}
var collection = oData.events.event;
var output = "<ul>";
collection.forEach(function(item, i, arr) {
output += "<li>" + item.description + "</li>";
if (i === arr.length-1) {
output += "</ul>";
$("#shower").append(output);
}
});

An array gets appended with undefined after `array.push`ing some strings to it. Is that normal?

I'm having trouble with a JavaScript array adding an extra undefined object after pushing some strings to the array.
$(function() {
var formTagArr = [];
$( "button", "#start-button" ).click(function() {
$.getJSON('http://127.0.0.1:8000/some_url/', function(data) {
formTagArr.push(buildForm(data));
console.log(formTagArr);
displayForm(formTagArr);
});
return false;
});
function buildForm(data) {
for (var i = 0; i < data.length; i++) {
var html = "";
var questionsTags = "<fieldset><p>" + data[i].question + "</p>";
var answersTags = "";
for (j = 0; j < data[i].answers.length; j++) {
answersTags += "<input type='radio' name='" + data[i].qid +
"' value='" + data[i].answers[j] + "' /" + ">" +
data[i].answers[j] + "\n";
}
html = questionsTags + answersTags + "</fieldset>";
formTagArr.push(html);
}
}
function displayForm(arr) {
if (arr.length === 0) {
return false;
}
var info = arr.pop();
$("#question-form").append(info[0]);
}
});
/some_url/ returns this JSON:
[{"qid": 4, "question": "How many legs does a spider have?", "answers": ["4", "6", "8", "10"]}, {"qid": 2, "question": "When did Nigeria become a republic?", "answers": ["1960", "1961", "1962", "1963"]}, {"qid": 1, "question": "When did Nigeria gain independence?", "answers": ["1960", "1961", "1962", "1963"]}, {"qid": 3, "question": "How many days are in a leap year?", "answers": ["360", "362", "365", "366"]}]
and console.log(formTagArr); in the code above returns:
["<fieldset><p>How many l...e='10' />10\n</fieldset>", "<fieldset><p>When did N...963' />1963\n</fieldset>", "<fieldset><p>When did N...963' />1963\n</fieldset>", "<fieldset><p>How many d...'366' />366\n</fieldset>", undefined]
Because of this, displayForm() fails since info is undefined. Of course I could just use a conditional to skip the undefined object but I want to know exactly how the undefined object got there in the first place.
What did i do wrong?
formTagArr.push(buildForm(data));
Your buildForm function doesn't return anything and the above code try to push the result of that function into the array. A function without a return statement would end up as undefined.
Seems like it should only be
buildForm(data)
As this function already pushed to the formTagArr array.
jsfiddle
You needed to remove the formTagArr.push call and also in the displayForm call change the line to this: $("#question-form").html(info);

Categories

Resources