I'm trying to create a json object in javascript containing dynamic values. I need to pass this JSON Object to server through an AJAX call. But I'm unable to add the dynamic values.
var finalJSONObj={};
for loop(int i = 0; i<10;i++){
// gets the values of rows i need to add ..
var taskValue = tasks[i]; // need to add this in the JSON Object
}
My final JSON object should look like:
finalJSONObj = {
tasks1: 'taskValue',
tasks2: 'taskValue',
tasks3: 'taskValue',
tasks4: 'taskValue',
userId: 'abcd',
date: '23/09/2016'
};
Need to add the "taskValue" retrieved from the for loop for each task in the JSON Object. Any Thoughts?
How about:
var finalJSONObj={};
for (var i = 0; i<tasks.length; i++) {
finalJSONObj[('tasks' + (i+1))] = tasks[i];
}
You are doing it wrong.
In forloop just change this syntax
var finalJSONObj={};
for loop(int i = 0; i<10;i++){
// gets the values of rows i need to add ..
finalJSONObj['task'+ (i + 1)] = tasks[i]; // need to add this in the JSON Object
}
Here key will be task + i which will be task1, task2 etc and value will be mapped to this key from your tasks array.
Related
I'm trying to get the "formatted_address" value from this
JSON file. I'm new to this and found the documentation quite confusing. The code I have now is the following where the variable "location" is the url generated like the one above.
$.getJSON(location, function( data ){
stad = data.results.formatted_address;
console.log(stad);
});
How would I achieve this?
results is an array, so you need to access it as one. Given your example with only one item, you can access it directly by index:
var stad = data.results[0].formatted_address; // = "'s-Hertogenbosch, Netherlands"
If there were multiple items in the array you would need to loop through them:
for (var i = 0; i < data.results.length; i++) {
var stad = data.results[i].formatted_address;
// do something with the value for each iteration here...
}
$.each(data.results,function(key,value){
console.log(value.formatted_address); //'s-Hertogenbosch, Netherlands
});
I'm trying to populate an array from a JSON feed. My code looks something like this:
// multiple arrays
var linje_1 = []
var linje_2 = []
// loop from json feed to populate array
for( var i = 0; i < data.length; i++) {
// I'm trying to "build" the array here. I know for sure that data[i] is good value that match the suffix of the array.
arrayname = 'linje_'+data[i];
arrayname.push({ label: data[i].x_+''+sid[a]+'', y: data[i].y_+''+sid[a]+'' })
}
Does anybody have any suggestions on how to solve the above?
The problem is that the code will not accept arrayname, but if I change and hardcode linje_1, everything works as expected.
When you define a variable arrayname = 'linje_'+data[i]; then its type is String. Strings are not arrays, you can't treat them like array, they don't have array methods.
If you want to dynamically construct the name of the variable, the best thing you can do is to use object and its keys:
var lines = {
linje_1: [],
linje_2: []
};
for (var i = 0; i < data.length; i++) {
var arrayname = 'linje_' + data[i];
lines[arrayname].push({ label: data[i].x_ + sid[a], y: data[i].y_ + sid[a]});
}
Also note, that I cleaned up the code a little (things like data[i].x_ + '' + sid[a] + '').
You're pushing data to a String, not an array. Try this:
window[arrayname].push(/* ... */);
if your variables are declared in the scope of the window, they can be referenced in multiple manners:
myArray
window.myArray
window['myArray'] // You want this one
You're using the same variable for an array and string.
arrayname = 'linje_'+data[i];
arrayname.push({ label: data[i].x_+''+sid[a]+'', y: data[i].y_+''+sid[a]+'' })
The variable arrayname is defined as a string, but then you call the push method which is only a method for arrays.
I am working on SpringMVC. In my controller I create a JSON object and I pass that object to JavaScript. How can I read that object in JavaScript?
My Map object
Map<String rootNode,List<String>> map = new HashMap<String rootNode,List<String>();
String rootNode = "bhanu";
ArrayList<String> al = new ArrayList<String>();
for( int i = 0; i < UserProfile.size; i++ ) {
al.add( userProfile.get( i ) );
}
map.put( userProfile, al );
At last my Map object has this data:
{
"Bhanu":["hari#gmail.com","balu#gmail.com","santha#gmail.com"],
"root":["bhanu#gmail.com","anu#gmail.com","apar#gmail.com"],
"hari":["bhanuprasad#gmail.com","sravya#gmail.com","mahesh#gmail.com"],
"balu":["rama#gmail.com"]
}
Now I convert this object with GSon:
Gson gson = new GSon();
String orgChartUsers = gson.toJson(map);
Now I passed this string to JavaScript because this is my Ajax response:
function orgUsers( result ) {
var orgObject = JSON.parse( result );
for(var name in result) {
console.log(name + "=" + result[name]);
}
}
This is working fine but i want to fetch data like this
first i want to fetch data from "root" in root i have some data when i read root for example i got bhanu#gmail.com now i want to fetch the data from Bhanu here i got some data like hari#gmail.com again i want to fetch data for hari like this i want how can i do this any one help me
Your lists will become javascript arrays, so for example you could use:
window.alert (orgObject["Bhanu"][0]);
which should pop up "hari#gmail.com" given your example data.
See How to list the properties of a JavaScript object for details of how to list the keys of your map, should you need this.
The result will be either an object or array.
To iterate over objects you can use the for-in loop
for (var key in obj) {
if(obj.hasOwnProperty(key)) {
// do something here
}
}
To iterate over an array you can use a normal loop:
for (var i = 0, ilen = array.length; i < ilen; i += 1) {
// do something here
}
Here is the most simple way
var result = {"Bhanu":["hari#gmail.com","balu#gmail.com","santha#gmail.com"],"root":["bhanu#gmail.com","anu#gmail.com","apar#gmail.com"],"hari":["bhanuprasad#gmail.com","sravya#gmail.com","mahesh#gmail.com"],"balu":["rama#gmail.com"]};
for(var name in result) {
console.log(name + "=" + result[name]);
}
This outputs:
Bhanu=hari#gmail.com,balu#gmail.com,santha#gmail.com
root=bhanu#gmail.com,anu#gmail.com,apar#gmail.com
hari=bhanuprasad#gmail.com,sravya#gmail.com,mahesh#gmail.com
balu=rama#gmail.com
Have in mind that the arrays are actually cast to a string. So result[name] is actually an array.
I have this JSON
[{"id":7,"serial":"7bc530","randomDouble":0.0,"randomDouble2":0.0,"randomDouble3":0.0,"date":1352228474000,"removed":null},
{"id":8,"serial":"4a18d27","randomDouble":0.0,"randomDouble2":0.0,"randomDouble3":0.0,"date":1352228474000,"removed":null},
{"id":9,"serial":"f30ef","randomDouble":0.0,"randomDouble2":0.0,"randomDouble3":0.0,"date":1352228474000,"removed":null},
{"id":10,"serial":"9e6d","randomDouble":0.0,"randomDouble2":0.0,"randomDouble3":0.0,"date":1352228474000,"removed":null},
{"id":11,"serial":"4d8665a3","randomDouble":0.0,"randomDouble2":0.0,"randomDouble3":0.0,"date":1352228474000,"removed":null},
{"id":12,"serial":"4fe1457","randomDouble":0.0,"randomDouble2":0.0,"randomDouble3":0.0,"date":1352228474000,"removed":null}]
and I have this JSON
{"computers":[{"id":"7bc530","name":"Dell","description":"Dell"},
{"id":"f30ef","name":"HP","description":"HP"},
{"id":"9e6d","name":"Compaq","description":"Compaq"},
{"id":"4d8665a3","name":"Toshiba","description":"Toshiba"},
{"id":"4fe1457","name":"Asus","description":"Asus"},
{"id":"4a18d27","name":"Acer","description":"Acer"}]}
I want to replace the "serial" element in the first JSON with the "Description" in this one. The reason why I need it in one JSON is that I am using a DataTable and I can only pass one JSON in.
I'm not sure how I can do this in Javascript / JQuery?
You can accomplish this without any jQuery by setting up small function:
(see the demo fiddle)
function replaceSerial (data1, data2) {
var descs = {}, computers = data2['computers'], final = data1;
for (var i = 0; i < computers.length; i++ ) {
descs[computers[i]['id']] = computers[i]['description'];
}
for (var i = 0; i < data1.length; i++) {
final[i]['serial'] = descs[data1[i]['serial']];
}
return final;
}
Then just save your two pieces of JSON into variables and invoke the function:
var json1, json2, mergedJson;
json1 = // DATA IN FIRST JSON;
json2 = // DATA IN SECOND JSON;
mergedJson = replaceSerial (json1, json2);
Assuming your first object is called to and the second object is called from
// Iterate over each entry in to
to.forEach(function(value) {
// In each iteration find elements in from where the id is the same
// as the serial of the current value of to
var description = from.computers.filter(function(element){
if (element.id == value.serial) return true;
});
// Copy description of first found object in the description property of
// the current object
value.description = description[0].description;
// Unset serial?
delete value.serial;
});
DEMO
Here is my response code in jQuery:
var response = $.parseJSON(response);
for (var i = 0; i < response.groupIds.length; i++) {
console.log(response.groupIds[i], i);
}
Each response.groupIds[i] is of the form {"unknown name":"unknown value"}.
I wish to access both of these bits of data in javascript, how do I accomplish this when I don't know in advance what e.g. unknown name is?
Use Object.keys to retrieve a full list (array) of key names. A polyfill is available here.
var group = response.groupIds[i];
var allPropertyNames = Object.keys(group);
for (var j=0; j<allPropertyNames.length; j++) {
var name = allPropertyNames[j];
var value = group[name];
// Do something
}
Your question's response format contains only one key-value pair. The code can then be reduced to:
var group = response.groupIds[i];
var name = Object.keys(group)[0]; // Get the first item of the list; = key name
var value = group[name];
If you're not interested in the list, use a for-i-in loop with hasOwnProperty. The last method has to be used, to exclude properties which are inherit from the prototype.
for (var name in group) {
if (group.hasOwnProperty(name)) {
var value = group[name];
// Do something
}
}
Use a for..in loop:
for( x in response.groupIds[i]) {
// x is now your unknown key
// response.groupIds[i][x] is the unknown value
}
Since there is only one property of the object, that'll work nicely.