I have this array that is returned by ajax:
console.log(res);
["07Apr|1", "06Apr|3", "05Apr|12", "04Apr|11", "03Apr|0", "02Apr|0", "01Apr|6", "31Mar|0", "30Mar|7", "29Mar|16", "28Mar|5", "27Mar|5", "26Mar|12", "25Mar|9", "24Mar|4", "23Mar|10", "22Mar|16", "21Mar|2", "20Mar|19", "19Mar|22", "18Mar|10", "17Mar|11", "16Mar|10", "15Mar|19", "14Mar|0", "13Mar|4", "12Mar|14", "11Mar|5", "10Mar|26", "09Mar|7", "08Mar|5"]
I convert this array using JSON.stringify:
(The variable "res" is the response of my ajax -as shown above)
var obj = [];
var daysBack = 30;
var objItem = {};
for(var x = 0; x <= daysBack; x++){
var currObj = res[x];
var objCombo = currObj.split("|");
var objItem = "{date: '"+objCombo[0]+"', downloads: '"+objCombo[1]+"'}";
objItem = JSON.stringify(eval("(" + objItem + ")"));
obj.push(objItem);
}
When I dump the "obj" to the console I get:
console.log(obj);
["{"date":"07Apr","downloads":"1"}", "{"date":"06Apr","downloads":"3"}", "{"date":"05Apr","downloads":"12"}", "{"date":"04Apr","downloads":"11"}", "{"date":"03Apr","downloads":"0"}", "{"date":"02Apr","downloads":"0"}", "{"date":"01Apr","downloads":"6"}", "{"date":"31Mar","downloads":"0"}", "{"date":"30Mar","downloads":"7"}", "{"date":"29Mar","downloads":"16"}", "{"date":"28Mar","downloads":"5"}", "{"date":"27Mar","downloads":"5"}", "{"date":"26Mar","downloads":"12"}", "{"date":"25Mar","downloads":"9"}", "{"date":"24Mar","downloads":"4"}", "{"date":"23Mar","downloads":"10"}", "{"date":"22Mar","downloads":"16"}", "{"date":"21Mar","downloads":"2"}", "{"date":"20Mar","downloads":"19"}", "{"date":"19Mar","downloads":"22"}", "{"date":"18Mar","downloads":"10"}", "{"date":"17Mar","downloads":"11"}", "{"date":"16Mar","downloads":"10"}", "{"date":"15Mar","downloads":"19"}", "{"date":"14Mar","downloads":"0"}", "{"date":"13Mar","downloads":"4"}", "{"date":"12Mar","downloads":"14"}", "{"date":"11Mar","downloads":"5"}", "{"date":"10Mar","downloads":"26"}", "{"date":"09Mar","downloads":"7"}", "{"date":"08Mar","downloads":"5"}"]
Now, I want to change the above array format from this one:
["{"date":"07Apr","downloads":"1"}", "{"date":"06Apr","downloads":"3"}", "{"date":"05Apr","downloads":"12"}", "{"date":"04Apr","downloads":"11"}", ....]
to that one:
[{"date":"07Apr","downloads":"1"}, {"date":"06Apr","downloads":"3"}, {"date":"05Apr","downloads":"12"}, {"date":"04Apr","downloads":"11"}, ....]
I mean to eliminate the double quotes that enclose the objects in curly braces.
Any ideas would be appreciated...
You can parse the data you received from the ajax response to create the array.
var populateArray = function (ajaxResponse) {
var newArray = [];
ajaxResponse.forEach(function (item, index) {
var props = item.split('|');
var obj = {
date: props[0],
downloads: props[1]
};
newArray.push(obj)
});
return newArray;
}
To demonstrate, try
console.log(populateArray(["07Apr|1", "06Apr|3", "05Apr|12", "04Apr|11", "03Apr|0", "02Apr|0", "01Apr|6", "31Mar|0", "30Mar|7", "29Mar|16", "28Mar|5", "27Mar|5", "26Mar|12", "25Mar|9", "24Mar|4", "23Mar|10", "22Mar|16", "21Mar|2", "20Mar|19", "19Mar|22", "18Mar|10", "17Mar|11", "16Mar|10", "15Mar|19", "14Mar|0", "13Mar|4", "12Mar|14", "11Mar|5", "10Mar|26", "09Mar|7", "08Mar|5"]));
Stringify the entire structure when it is ready, not segments.
Don't use eval ever, use JSON.parse() instead.
var obj = [];
var daysBack = 30;
var objItem = {};
for(var x = 0; x <= daysBack; x++){
var currObj = res[x];
var objCombo = currObj.split("|");
var objItem = {date: objCombo[0], downloads: objCombo[1]};
//objItem = JSON.stringify(eval("(" + objItem + ")"));
obj.push(objItem);
}
obj = JSON.stringify(obj);
Related
I am trying to remove the $ symbol from the key in json object(parsed). Normal JS file I used Remove special character in json key name in nodejs this answer mentioned and it is working fine. But I tried in nodejs due to async it is not working properly. The last formed object did not contain the entire modified value. So I tried the original function which is posted in the question but I am getting callback function not found error. I am using node 10.19 version. Is there any other way I can remove the $ symbol from my json object. Please give me a working solution. Actualy I am getting the input from yml file which gets converted to json string in jenkins. And again In my code I have parsed it. If there any library to directly convert yml file to json in jenkins that will also help.
var obj = {
'blue':{
'test:"value',
'$test1':'value1',
'tiger':'cheetah_growl',
'$jan':'cool'
}
}
Normal js file
var obj_new = { '$name': 'test1', '$auth_users': 'bajali_s' };
console.log("obj.blue",obj.blue.tiger);
var str = obj.blue.tiger;
var res = str.replace("_", " ");
console.log("res",res);
obj.blue.tiger = res;
console.log("obj.blue",obj.blue.$test1);
//const obj1 = {"example1.":"sometext.","example2.":"anothertext."};
const obj2 = {};
console.log(Object.getOwnPropertyNames(obj));
const obj1 = obj_new;
console.log("__",obj1);
/* for (const key of Object.getOwnPropertyNames(obj1)) {
obj2[key.replace(/[|&;$%#."<>()+,]/g, "")] = obj1[key];
} */
for (const key of Object.getOwnPropertyNames(obj1)) {
obj2[key.replace(/[|&;$%#."<>()+,]/g, "")] = obj1[key];
}
console.log("==",obj2);
var newjson = JSON.stringify(obj2);
console.log(newjson);
Here is what I did to remove the extra symbol in the key and value. I went through many sites and came up with this procedure hope it helps someone. I have also made it little dynamic.
var special_char_keys = ["creationType", "vm_location", "nic_location", "vnetlocation", "rg_location"];
var elements_to_delete = ["blueprint_info", "riglet_info", "quick_links"];
for (var a = elements_to_delete.length; a >= 0; a--) {
delete cloudProperties[elements_to_delete[a]];
}
var Mainkeys = Object.keys(cloudProperties);
console.log("Mainkeys", Mainkeys);
var total_keys_cloudproperties = Mainkeys.length;
for (var j = total_keys_cloudproperties; j > 0; j--) { // main json loop starts
for (const key of Object.getOwnPropertyNames(cloudProperties)) { // getting the main json keys
var obj1 = cloudProperties[key];
var obj2 = {};
var obj3 = {};
var obj4 = {};
var obj5 = {};
var formattedarray = [];
var keys = Object.keys(cloudProperties[key]);
//console.log("inner keys", keys);
var tasksToGo = keys.length;
//console.log("key length",tasksToGo);
for (var i = tasksToGo; i > 0; i--) {
for (const key1 of Object.getOwnPropertyNames(obj1)) {
// var item = obj1.get(key1); // this will get the value in the json based on key
if (Array.isArray(obj1[key1])) { // checking whether the key has value as [{},{}]
// console.log("for jsonarray case");
var temparray = obj1[key1]; // assigning the array to temparray
for (var k = 0; k < temparray.length; k++) { // for loop for getting each object value
var obj3 = temparray[k]; // assigning the inner object to a variable
var Arraykeys = Object.keys(obj3);
// console.log("array inner keys", Arraykeys);
var tasksToGo1 = Arraykeys.length;
for (var t = tasksToGo1; t > 0; t--) {
for (const key2 of Object.getOwnPropertyNames(obj3)) {
if (special_char_keys.includes(key2)) {
var tempvalue = obj3[key2];
var newvalue = tempvalue.replace("_", " ");
// console.log("newvalue", newvalue);
obj4[key2.replace(/[|&;$%#."<>()+,]/g, "")] = newvalue;
} else {
obj4[key2.replace(/[|&;$%#."<>()+,]/g, "")] = obj3[key2];
}
// obj4[key2.replace(/[|&;$%#."<>()+,]/g, "")] = obj3[key2];
}
if (Arraykeys == tasksToGo1) {
break;
}
temparray[k] = obj4;
// console.log("temparray[k] ======================", temparray[k]);
}
}
obj5[key1] = temparray;
cloudProperties[key] = obj5;
// console.log("vm case", cloudProperties[key]);
} else {
// console.log("for normal case");
if (special_char_keys.includes(key1)) {
var tempvalue = obj1[key1];
// console.log(obj1[key1]);
var newvalue = tempvalue.replace("_", " ");
// console.log("newvalue", newvalue);
obj2[key1.replace(/[|&;$%#."<>()+,]/g, "")] = newvalue;
cloudProperties[key] = obj2;
} else {
obj2[key1.replace(/[|&;$%#."<>()+,]/g, "")] = obj1[key1];
cloudProperties[key] = obj2;
}
//obj2[key1.replace(/[|&;$%#."<>()+,]/g, "")] = obj1[key1];
// cloudProperties[key] = obj2;
}
}
}
//console.log("obj2",obj2);
//console.log("+++++++++++++++++",cloudProperties[key]);
}
if (j == total_keys_cloudproperties) {
//console.log("inside break");
break;
}
}
console.log("After removing", cloudProperties);
So right now this is my current code and I'm trying to figure out a way to loop through the variables I've already declared (Assuming variables 1-9 already have values). I just wanted to know whether this was possible at all?
var title;
var brief;
var hover;
var whatTitle;
var whatDesc;
var whyTitle;
var whyDesc;
var funTitle;
var funDesc;
var titles = [];
var briefs = [];
var hovers = [];
var whatTitles = [];
var whatDescs = [];
var whyTitles = [];
var whyDescs = [];
var funTitles = [];
var funDescs = [];
var obj = {'titles' : title};
if(localStorage.getItem('titles') != null) {
var tmp = JSON.parse(localStorage.getItem('titles'));
for(var i = 0;i<tmp.length;i++) {
titles.push(tmp[i]);
}
}
titles.push(obj);
localStorage.setItem("titles", JSON.stringify(titles));
Output I want if we printed out the looped code:
var obj = {'titles' : title};
if(localStorage.getItem('titles') != null) {
var tmp = JSON.parse(localStorage.getItem('titles'));
for(var i = 0;i<tmp.length;i++) {
titles.push(tmp[i]);
}
}
titles.push(obj);
localStorage.setItem("titles", JSON.stringify(titles));
var obj = {'briefs' : brief};
if(localStorage.getItem('briefs') != null) {
var tmp1 = JSON.parse(localStorage.getItem('briefs'));
for(var i = 0;i<tmp.length;i++) {
briefs.push(tmp[i]);
}
}
briefs.push(obj);
localStorage.setItem("briefs", JSON.stringify(briefs));
var obj = {'hovers' : hover};
if(localStorage.getItem('hovers') != null) {
var tmp2 = JSON.parse(localStorage.getItem('hovers'));
for(var i = 0;i<tmp.length;i++) {
hovers.push(tmp[i]);
}
}
hovers.push(obj);
localStorage.setItem("hovers", JSON.stringify(hovers));
...etc
If the code is running in a browser, then you can do something like:
for(key in window) { console.log(window[key]) } // print all variables
The variables are associated to the global namespace. That is to say the upmost "this" reference or the window object.
You're almost there with the code you have. If you look at your "desired output" examples, you'll see that the only thing that really differs between each element of your "unrolled loop" is the key for local storage ('titles', 'briefs', 'hovers').
With that in mind, you could use an Object to map the keys to the variables you have at the top level. So this:
var titles = [];
var briefs = [];
var hovers = [];
var whatTitles = [];
var whatDescs = [];
...
Becomes (UPDATE: with the initializer values preserved):
var key_to_collection = {
'titles': [title],
'briefs': [brief],
'hovers': [hovers],
'whatTitles': [whatTitles],
'whatDescs': [whatDescs],
}
Then, you loop over the values of this object:
Object.keys(key_to_collection).forEach(function(key) {
var obj = {};
collection = key_to_collection[key];
obj[key] = collection;
if(localStorage.getItem(key) != null) {
var tmp = JSON.parse(localStorage.getItem(key));
for(var i = 0;i<tmp.length;i++) {
collection.push(tmp[i]);
}
}
collection.push(obj);
localStorage.setItem(key, JSON.stringify(collection));
});
If your variable name is title for example, then you can access it using window['title']. This means that if you define an array of your global variable names:
const varNames = ['title', 'brief', 'hover', ...]
Then you can do a loop like the following
for(const name of varNames) {
const value = window[name]
// do whatever you want using the variable name and value
}
I hope this solves your issue :)
I need to retrieve variables from an URL.
I use this found function:
function getParams(str) {
var match = str.replace(/%5B/g, '[').replace(/%5D/g, ']').match(/[^=&?]+\s*=\s*[^&#]*/g);
var obj = {};
for ( var i = match.length; i--; ) {
var spl = match[i].split("=");
var name = spl[0].replace("[]", "");
var value = spl[1];
obj[name] = obj[name] || [];
obj[name].push(value);
}
return obj;
}
var urlexample = "http://www.test.it/payments/?idCliente=9&idPagamenti%5B%5D=27&idPagamenti%5B%5D=26"
var me = getParams(stringa);
The output is:
{"idPagamenti":["26","27"],"idCliente":["9"]}
But idCliente is always NOT an array, so i'd like to retrieve:
{"idPagamenti":["26","27"],"idCliente": 9 }
This is the fiddle example
function getParams(str) {
var match = str.replace(/%5B/g, '[').replace(/%5D/g, ']').match(/[^=&?]+\s*=\s*[^&#]*/g);
var obj = {};
for ( var i = match.length; i--; ) {
var spl = match[i].split("=");
var name = spl[0].replace("[]", "");
var value = spl[1];
obj[name] = obj[name] || [];
obj[name].push(value);
}
return obj;
}
var stringa = "http://www.test.it/payments/?idCliente=9&idPagamenti%5B%5D=27&idPagamenti%5B%5D=26"
var me = getParams(stringa);
$(document).ready(function(){
alert("testing");
console.log(me);
$(".a").html(JSON.stringify(me));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="a">
</div>
Someone can help me to modify code?
I think your facing a real paradigm problem. Why idCliente wouldn't be an array but idPagamenti would be. You should have all array or none but not both. getParams() function can make this choice for you and you should probably change the way you are working with this.
Anyway, here is a getParams() function that replace any single-valued array to a value. Note that if you have only one idPagamenti in your URI, you will also have a single value for idPagamenti instead of an array.
function getParams(str) {
var match = str.replace(/%5B/g, '[').replace(/%5D/g, ']').match(/[^=&?]+\s*=\s*[^&#]*/g);
var obj = {};
for ( var i = match.length; i--; ) {
var spl = match[i].split("=");
var name = spl[0].replace("[]", "");
var value = spl[1];
obj[name] = obj[name] || [];
obj[name].push(value);
}
Object.keys(obj).forEach(key => {
if (obj[key].length === 1) {
obj[key] = obj[key][0];
}
})
return obj;
}
var urlexample = "http://www.test.it/payments/?idCliente=9&idPagamenti%5B%5D=27&idPagamenti%5B%5D=26"
var me = getParams(stringa);
If you know that you will always get ids as parameters, you can also add a parseInt() for each parameter by replacing var value = spl[1]; with var value = parseInt(spl[1], 10);
I need to get the var i need to be appended to the left side of the object declaration. I am unable to find how to append that. Kindly help me to get rid of the Error.
If any Other Solution available also i will follow it up.
I have tried the below code
<script type="text/javascript">
var text_count=5;
var textbox = new Object();
for (var i = 1; i<=text_count; i++)
{
textbox.meta_key_textbox='Meta Key';
textbox.meta_key_value_textbox='Meta Value';
};
var textbox_string = JSON.stringify(textbox);
alert(textbox_string);
</script>
I get the last Value alone in this. But I am unable to get all the Values that are in the Loop.
But when i do this method manually it works. Kindly Clarify on this.
<script type="text/javascript">
var text_count=5;
var textbox = new Object();
textbox.meta_key_textbox='Meta Key';
textbox.meta_key_value_textbox='Meta Value';
textbox.meta_key_textbox1='Meta Key One';
textbox.meta_key_value_textbox1='Meta Value One';
var textbox_string = JSON.stringify(textbox);
alert(textbox_string);
</script>
you assign the same value in each iteration, use the below code:
<script type="text/javascript">
var text_count=5;
var textbox = new Object();
for (var i = 1; i<=text_count; i++)
{
var text = "meta_key_textbox" + i;
var value_text = "meta_key_value_textbox" + i;
textbox.text='Meta Key';
textbox.value_text='Meta Value';
};
var textbox_string = JSON.stringify(textbox);
alert(textbox_string);
</script>
var text_count=5;
var textbox = new Object();
var arrKey = [];
var arrValue = [];
var values = ["one", "two", "three", "four"];
for (var i = 1; i<text_count; i++) {
arrKey.push({key: "textbox.meta_key_textbox" + i, value: values[i-1]});
arrValue.push({key: "textbox.meta_key_value_textbox" + i, value: values[i -1]});
}
textbox.meta_key_textbox='Meta Key';
textbox.meta_key_value_textbox='Meta Value';
for (var i = 1; i<text_count; i++)
{
textbox[arrKey[i-1].key]= 'Meta Key ' + arrKey[i-1].value;
textbox[arrValue[i-1].key]= 'Meta Value ' + arrValue[i-1].value;
};
var textbox_string = JSON.stringify(textbox);
alert(textbox_string);
I have these following arrays
var category = ['Guitar', 'Bass', 'Amps'];
var platform_a = ['platform-a1','platform-a2','platform-a3'];
var platform_b = ['platform-b1','platform-b2','platform-b3'];
var platform_c = ['platform-c1','platform-c2','platform-c3'];
And I want to convert them into a json which should look like this
{
"Guitar":["platform-a1","platform-a2","platform-a3"],
"Bass":["platform-b1","platform-b2","platform-b3"],
"Amp":["platform-c1","platform-c2","platform-c3"]
}
How would I do this? I would have to do this in pure javascript
Let's present three different approaches to your case:
First one
If you want just to create the json object with your data try:
http://jsfiddle.net/csdtesting/tap2xom9/
var platform_a = ['platform-a1', 'platform-a2', 'platform-a3'];
var platform_b = ['platform-b1', 'platform-b2', 'platform-b3'];
var platform_c = ['platform-c1', 'platform-c2', 'platform-c3'];
var category = ['Guitar', 'Bass', 'Amps'];
var obj = {
Guitar: platform_a,
Bass: platform_b,
Amps: platform_c
};
document.write(JSON.stringify(obj));
Second
If you want to create it dynamically do something like that:
http://jsfiddle.net/csdtesting/tap2xom9/
var category = ['Guitar', 'Bass', 'Amps'];
var platform_a = ['platform-a1', 'platform-a2', 'platform-a3'];
var platform_b = ['platform-b1', 'platform-b2', 'platform-b3'];
var platform_c = ['platform-c1', 'platform-c2', 'platform-c3'];
var FinalObject = {};
FinalObject[category[0]] = platform_a;
FinalObject[category[1]] = platform_b;
FinalObject[category[2]] = platform_c;
document.write(JSON.stringify(FinalObject));
Finally
If you want to be more dynamic then try this :
http://jsfiddle.net/csdtesting/kqwz72os/
var FinalObject = {};
var category = ['Guitar', 'Bass', 'Amps'];
var platforms = {
platform_a: ['platform-a1', 'platform-a2', 'platform-a3'],
platform_b: ['platform-b1', 'platform-b2', 'platform-b3'],
platform_c: ['platform-c1', 'platform-c2', 'platform-c3']
};
for (var i = 0; i < category.length; i++) {
FinalObject[category[i]] = platforms[Object.keys(platforms)[i]];
}
document.write(JSON.stringify(FinalObject));
Hope this helps!
There's no reasonable shortcut here. You just have to do it manually:
var jsonString = JSON.stringify({
"Guitar": platform_a,
"Base": platform_b,
"Amp": platform_c
});