Dictionary in JavaScript - javascript

Currently I tried to reform my JSON data to a dictionary to store only needed data in an array with key and value.
* Edit to put my full code. *
This is how I do:
var myData = [];
var urlPath = "https://tipjira.pgdev.abcd.com/rest/api/2/search?jql=project=GRIFR14%2Band%2BfixVersion=15018";
var jiraMapping = [];
$.ajax({
url : "http://frparwself22.dhcp.par.abcd.com:8080/jiraproxy/jira?url=" + urlPath,
dataType : 'json',
type: 'GET',
success : function(data) {
for (var i=0; i<data.issues.length; i++) {
var obj = {};
obj[data.issues[i].key] = data.issues[i].self;
jiraMapping.push(obj);
alert(jiraMapping.length);
}
},
error : function() {
alert("Error!")
}
});
alert(jiraMapping.length);
My original data is {issues:[{...,"self":"/rest/api/2/issue/175074","key":"GRIFR14-36",...}, {...,"self":"/rest/api/2/issue/175075","key":"GRIFR14-37",...}, ...]}. And I want to reform to have the array with key and value which are key and self.
So the data in my jiraMapping should be something like [{k1:v1}, {k2,v2}, ...].
But when I tired to print the length of jiraMapping, the length is 0.
I tried to put alert to check key and value that I add to the array and the values exist.
I don't know where is the problem exactly. Please help...

Without knowing exactly what information you're passing in, it's hard to say what's going wrong. That being said, my first guess is that data/myData isn't formatted the way you think. For instance, if myData.issues.length is 0, nothing in the loop will get executed.
There's also a chance that you're never actually running the success function. Could you post some more code?

The problem lies in the data that you are receiving or you have a typo somewhere later when checking length. This all looks fine, and I tried to replicate your problem like this:
var jiraMapping = [];
var myData = [{"A":"a"},{"B":"b"}];
for (var i=0; i<myData.length; i++) {
var obj = {};
obj[myData[i]] = myData[i];
jiraMapping.push(obj);
}
console.log(jiraMapping);
but this works fine, fiddle here: http://jsfiddle.net/GWpBs/2/

Related

Am I building the JavaScript objects correctly for a JSON string array?

In JavaScript I have the following code:
for (i = 1; i<3; i++)
{
// above I collect check_a and check_b through radio button responses.
var connectJSON = ",";
var passObj = {id:i, ask:check_a, description:check_b};
// adding object string together in tempObj
var tempObj = tempObj + connectJSON + passObj;
}
// get ready for transport to server and display result of string
var data = JSON.stringify(tempObj);
console.info("info: " + data);
// post string to server
$.ajax
({
type: 'POST',
url: 'out.php',
data: {data: data},
success: function(msg)
{
alert(msg);
}
});
In out.php I try to determine the result back from the server. The code is as follows:
<?php
if (ISSET($_POST['data']))
{
echo "TRUE";
}
ELSE
{
echo "False";
}
var_dump($_POST['data']);
?>
I am getting this message, AJAX alert (msg) :
**True** string(42) ""question, [object Object], [object Object]""
Apparently this message is describing the string array being passed.
What I now need to do, if the format is correct, is to be able to access the string array - maybe with JSON_decode and identify properties of the array so that I can make insertions into a MySQL database.
Thanks for any AND all help...
var connectJSON = ",";
var passObj = {id:i, ask:check_a, description:check_b};
// adding object string together in tempObj
var tempObj = tempObj + connectJSON + passObj;
First of all. If you just test this part in the console you will see that if you concatenate JS object and the string ',' you get the string "[object Object],[object Object]". You need to first stringify the JS object before concatenating it with strings.
Second I can really seem to understand your code but looping that code will just override those variables because they are declared in the loop so that doesn't seem correct. Probably you want to get the declarations out of the loop.
Otherwise it's kind of like this - you stringify the Js object and pass it as data to the ajax.
No. To build JSON, first build a valid structure, then use JSON.stringify on the result; don't convert to string while building the structure. connectJSON + passObj will force passObj to string, resulting in "[object Object]".
Instead:
var array = []; // <== An empty array
for (i = 1; i<3; i++)
{
// Push entries into the array
array.push({id:i, ask:check_a, description:check_b});
}
// Convert to JSON
var data = JSON.stringify(array);
Side note: The code in your question didn't declare i anywhere. If your real code doesn't, it's falling prey to The Horror of Implicit Globals.* Be sure to declare your variables. :-)
* (that's a post on my anemic little blog)
The issue is here var tempObj = tempObj + connectJSON + passObj;. You are concatinating objects and strings. In that case JavaScript will use Object.prototype.toString() first and then do the concatination. and Object.prototype.toString() in case of objects will produce [object Object]. To fix this you have to create an array like below.
var tempObj = [];
for (i = 1; i < 3; i++) {
// above I collect check_a and check_b through radio button responses.
var connectJSON = ",";
var passObj = {
id: i,
ask: check_a,
description: check_b
};
tempObj.push(passObj);
}
Also, you can skip JSON.stringify() and directly submit the JS object.
I'm trying to understand how is this deceleration :
var tempObj = tempObj + etc...;
possible ?
you cant set the value of something you just declared,
to the same thing you just declared .

How to get "Column Name" and "Previous Value" from Cell Editing Grid

I have a grid for which Cell editing plugin has been activated.
Once I updated few of the columns, I press Save button and all of the updated records (Row) are sent back with following code:
var grid = Ext.ComponentQuery.query('#CheckGrid')[0];
var store = Ext.data.StoreManager.lookup('CheckStore');
var modifieds = grid.getStore().getUpdatedRecords();
var id_check = [];
var ds_check_list = [];
var id_check_type = [];
var id_version = [];
console.log(modifieds);
if (modifieds.length > 0)
{
for(var i = 0; i < modifieds.length; i++) {
id_check.push(modifieds[i].get('ID_CHECK'));
ds_check_list.push(modifieds[i].get('DS_CHECK_LIST'));
id_check_type.push(modifieds[i].get('ID_CHECK_TYPE'));
id_version.push(modifieds[i].get('ID_VERSION'));
}
}
Ext.Ajax.request({
url: 'URL',
method: 'POST',
params: {
'Param.1': 'Check',
'Param.2': id_check.toString(),
'Param.3': ds_check.toString(),
'Param.4': id_type.toString(),
'Param.5': id_version.toString()
}
This works fine. But I want to know and send also the column name which got updated and its previous value.
When I see the console for console.log(modifieds); , I can spot following:
So how do I access this previousValue object in my code? I want to know previous value as well as column name both.
Kindly advise !
ds_check_list.push(modifieds[i].getPrevious('DS_CHECK_LIST'));
id_check_type.push(modifieds[i].getPrevious('ID_CHECK_TYPE'));
Ext.data.Model.getPrevious(fieldname) : Object
This method returns the value of a field given its name prior to its most recent change.
The Store.getUpdatedRecords() function returns an Ext.data.Model instance, which in turn has a getPrevious method.
It usually helps a lot to take a look at the API docs of ExtJS and then just navigating through the methods and return values used.
The getUpdatedRecords() method is documented over here: http://docs.sencha.com/extjs/5.0/5.0.1-apidocs/#!/api/Ext.data.Model-method-getPrevious

Problems with sending array through ajax

Hello stackoverflow community, I need help with my JavaScript. How can I transfer array with id of kasce?
When I'm printing array in ajax_import.php file, it prints nothing. So probably my array is empty.
Here is my code:
function SubmitImp() {
var import_tasken = document.getElementById("import_tasken");
//import_tasken.style.display = "none";
var kasce = document.getElementsByName("impTaskCh");
var array = "";
for (i = 0; i < kasce.length; i++) {
array[i] = kasce[i].getAttribute('id');
}
$.ajax({
type: "POST",
url: 'modules/projects/ajax/ajax_import.php',
data: {
data: array,
},
success: function(data)
{
alert("Viskas ok!");
}
});
}
A couple of problems there.
First, you're not sending an array, you're sending a blank string.. Here, you put a string in array:
var array = "";
Later, you do this:
array[i] = kasce[i].getAttribute('id');
...which is trying to assign a new value to a single character of the string. You can't do that, strings are immutable in JavaScript; the line ends up not changing the string at all.
array[i] is a single character in the string. You're trying to assign a string to it.
To make array an array, use:
var array = [];
Next, and this may not be a problem, here:
data: {
data: array,
}
...you're telling jQuery to send a URI-encoded parameter called data with the value array. jQuery will call toString on array, which with a true array ends up being Array#join. That may well be what you want, you'll get something like this:
firstId,secondId,thirdId
Your PHP should look for it as $_POST['data'].
Side note: You're falling prey to The Horror of Implicit Globals because you never declare your i variable. You want to declare it.

How can I assign a JavaScript variable by parsing a JSON file?

I have a database server that will be running a script to generate this given file daily:
{"data": [
{"variable":"var1","value": "123"},
{"variable":"var2","value": "456"},
{"variable":"var3","value": "789"}]}
I am trying to parse this file to set three javascript variables for a HTML canvas element.
So far, I'm thinking I'll parse the JSON file
var JSONfile = './file.json';
var getData = JSON.parse(JSONfile);
Then a for loop to assign the variables
for (i = 0; i < getData.length; i++) {
var getData.variable=getData.Value;
}
And I'm hoping to get results of:
var var1 = 123;
var var2 = 456;
var var3 = 789;
But var getData.variable=getData.Value; breaks. What am I missing?
JSON.parse() expects a JSON string, when you are passing it a file.
The first thing you need to do is use AJAX to get the contents of the file into a variable. Either use a library like jQuery (see http://api.jquery.com/jquery.getjson/) or from scratch in JavaScript. But don't waste your time on the "from scratch" version unless you have to.
Use jQuery to get the contents of the file into an object, and pass the inner data (an array) to a function called doSomething():
$(function () {
$.getJSON("./file.json", function (data) {
}).success(function (data) {
myArr = data.data;
doSomething(data.data);
});
});
Here, you iterate through the passed array, which contains elements that have a .variable and a .value property. This writes both properties of each element to the console, for your viewing pleasure:
function doSomething(arr) {
for (i = 0; i < arr.length; i++) {
console.log(arr[i].variable + ': ' + arr[i].value);
}
}
You can also access the properties directly by the index as follows:
alert(jsonFromFile.data[2].variable); // Will alert "var3"
alert(jsonFromFile.data[2].value); // Will alert "789"

JavaScript/jQuery solution for looping through JSON objects

I have this kind of JSON sent from PHP:
{"status":"error","message":"Firstname is invalid"}{"status":"error","message":"Lastname is invalid"}{"status":"success","message":"Middle name is fine"}
Ajax is retrieving me that in the success thingy:
success:function(data){
data=JSON.parse(data);
//need to loop trough data here
}
so the problem is that I need to console.log(data.status /* AND */ data.message) at once.
(ignore the comment above)
So in the JSON example above I want to be able to console.log the following:
(1) error Firstname is invalid
(2) error Lastname is invalid
(3) success Middle name is fine
(the above numbers in "()" just means how it should look like in the console thingy in chrome. I don't need to have them actually numbered)
////////
What I am actually trying to accomplish is to display the success/error messages with alrtify.js based on status.value (wither success or error). I don't want to display them all in one notification. I want each of the error/success appear as separate notification. I need to loop through them for that.
Please have a look on your JSON format. It should be like :
[{"status":"error","message":"Firstname is invalid"},{"status":"error","message":"Lastname is invalid"},{"status":"success","message":"Middle name is fine"}];
So ultimately you will be able to loop.
var data = [{"status":"error","message":"Firstname is invalid"},
{"status":"error","message":"Lastname is invalid"},
{"status":"success","message":"Middle name is fine"}];
for(var i in data)
{
console.log(data[i].message)
}
Assuming that what you are actually receiving is an array rather than that invalid JSON that you've shown there:
success:function(data){
data=JSON.parse(data); // you probably shouldn't be using this line
data.forEach(function (item) {
console.log(item.status + ' ' + item.message);
});
}
This code works like a charm for me.
Plase pay attention, that in my string objects are divided by comma, instead of yours '{"status":"error","message":"Firstname is invalid"}{"status":"error","message":"Lastname is invalid"}{"status":"success","message":"Middle name is fine"}'
var data = '[{"status":"error","message":"Firstname is invalid"}, {"status":"error","message":"Lastname is invalid"}, {"status":"success","message":"Middle name is fine"}]';
var parsedData = JSON.parse(data);
parsedData.forEach(function(item, index) {
alert(item.status + " - " + item.message);
console.log(item.status + " - " + item.message);
});
success:function(data){
data=JSON.parse(data); // you probably shouldn't be using this line
var data = $.parseJSON(item);
for (var i=0; i < data.length; i++){
var obj = data[i];
var status = obj.status;
var message = obj.message;
}
});

Categories