Convert object from localstorage into text - javascript

I am outputting objects from a localstorage and I get:
"[{\"title\":\"q\",\"ingredients\":\"s\",\"instructions\":\"d\",\"moreingredients\":[],\"moreinstruction\":[],\"img\":{\"jQuery3110052397224993886441\":{\"display\":\"\"}}},{\"title\":\"q\",\"ingredients\":\"w\",\"instructions\":\"e\",\"moreingredients\":[],\"moreinstruction\":[],\"img\":{\"jQuery311079670549304635711\":{\"display\":\"\"}}},{\"title\":\"q\",\"ingredients\":\"w\",\"instructions\":\"e\",\"moreingredients\":[],\"moreinstruction\":[],\"img\":{\"jQuery311016424488798697091\":{\"display\":\"\"}},\"salutation\":\"polish\"},{\"title\":\"q\",\"ingredients\":\"q\",\"instructions\":\"a\",\"moreingredients\":[],\"moreinstruction\":[],\"img\":{\"jQuery311067483883379310751\":{\"display\":\"\"}},\"salutation\":\"italian\"},{\"title\":\"q\",\"ingredients\":\"w\",\"instructions\":\"e\",\"moreingredients\":[],\"moreinstruction\":[],\"img\":{\"jQuery3110317360085863979571\":{\"display\":\"\"}},\"salutation\":\"polish\"}]"
However I want to get rid of all the brackets and only have the actual text so instead of
{\"title\":\"q\"
I want q on the page.
var salt;
$("#salutation").change(function() {
salt = $(this).children(":selected").attr("id");
});
var existingData = JSON.stringify(localStorage.getItem("key")) || [];
document.getElementById("qq").innerHTML +=(existingData);
$('form').submit(function() {
var newArray = [];
$(".add_id2").each(function(){
newArray.push($(this).val());
});
var newArray2 = [];
$(".add_id").each(function(){
newArray2.push($(this).val());
});
var existingData = JSON.parse(localStorage.getItem("key")) || [];
var newData = {
'title': $("#title").val(),
'ingredients': $("#ingredients").val(),
'instructions': $("#inst").val(),
'moreingredients': newArray,
'moreinstruction': newArray2,
'img': img,
'salutation': salt,
};
existingData.push(newData);
localStorage.setItem("key", JSON.stringify(existingData));

Values from localStorage are always stored as strings. You need to use JSON.parse() to convert he string into a valid object, then you can use a for loop to iterate over the json to get the title using json[i].title:
var json = "[{\"title\":\"q\",\"ingredients\":\"s\",\"instructions\":\"d\",\"moreingredients\":[],\"moreinstruction\":[],\"img\":{\"jQuery3110052397224993886441\":{\"display\":\"\"}}},{\"title\":\"q\",\"ingredients\":\"w\",\"instructions\":\"e\",\"moreingredients\":[],\"moreinstruction\":[],\"img\":{\"jQuery311079670549304635711\":{\"display\":\"\"}}},{\"title\":\"q\",\"ingredients\":\"w\",\"instructions\":\"e\",\"moreingredients\":[],\"moreinstruction\":[],\"img\":{\"jQuery311016424488798697091\":{\"display\":\"\"}},\"salutation\":\"polish\"},{\"title\":\"q\",\"ingredients\":\"q\",\"instructions\":\"a\",\"moreingredients\":[],\"moreinstruction\":[],\"img\":{\"jQuery311067483883379310751\":{\"display\":\"\"}},\"salutation\":\"italian\"},{\"title\":\"q\",\"ingredients\":\"w\",\"instructions\":\"e\",\"moreingredients\":[],\"moreinstruction\":[],\"img\":{\"jQuery3110317360085863979571\":{\"display\":\"\"}},\"salutation\":\"polish\"}]";
json = JSON.parse(json);
console.log(json);
for (var i = 0; i < Object.keys(json).length; i++) {
console.log("Title is: " + json[i].title);
}

Related

Javascript: Parse string array into object with custom key names and values

So I have a string which contains a list of custom http headers that is in the following format:
var headers = "Referer=SomeValue|User-Agent=SomeUserAgent";
I split that up using the pipe as a delimiter:
var splitHeaders = headers.split("|");
I'm left with an array which I can loop through, and I'm trying to convert that string array into an object. This is what I have so far:
var customHeaders = {};
for (var i in splitHeaders) {
var data = splitHeaders[i].split("=");
customHeaders[data[0]] = data[1];
}
What I'm essentially trying to create is an object called customHeaders to hold values like:
customHeaders = {
"Referer":"https://someurl.com/",
"User-Agent":"Some Browser"
};
Am I doing something wrong?
You are on the right track. Use a more standard form of the for loop using the length of the splitHeaders as a limiter:
for (var i = 0; i < splitHeaders.length; i++) {
Working example:
var headers = "Referer=SomeValue|User-Agent=SomeUserAgent";
var splitHeaders = headers.split('|');
var customHeaders = {};
for (var i = 0; i < splitHeaders.length; i++) {
var data = splitHeaders[i].split("=");
customHeaders[data[0]] = data[1];
}
console.log(customHeaders);
There are also other methods you can use that allow you to convert an array of items into an object, using such as reduce.
var headers = "Referer=SomeValue|User-Agent=SomeUserAgent";
headers = headers
.split('|')
.reduce(function(obj, val) {
var split = val.split('=');
obj[split[0]] = split[1];
return obj;
}, {});
console.log(headers);

Convert Array to JSON Array

How do I convert
["ID:2","ID:3","ID:4"]
to
[{
"ID":2
},
{
"ID":3
},
{
"ID":4
}]
because this type of data i have to send to my webservice
For getting an array with objects, you could split the strings and build a new object with the wanted property and the numerical value.
var data = ["ID:2","ID:3","ID:4"],
result = data.map(function (s) {
var p = s.split(':'),
t = {};
t[p[0]] = +p[1];
return t;
});
console.log(result);
var newArrayOfObjs =arr.map((item)=> {
var obj = {};
var splitItems = item.split(':');
obj[splitItems[0]] = splitItems[1];
return obj;
}
You'll have to split the string on ':' and set the 0th element as key and 1st element as value.
var aryExample = ["ID:2","ID:3","ID:4"], aryNew = [];
for( var i in aryExample ) {
aryNew.push({ID:Number(aryExample[i].split(":")[1])});
}
console.dir(aryNew);
That should do it.

unwanted keys in JSON object

hi i am creating a JSON object after executing a loop. the problem is the JSON object have additional keys. i don't want that keys. that keys are generated by me. for arraigning the json according my requirement. this is code i am using for create my JSON object
var bankdata = data;
var updatebankdata = {}
for (var key in bankdata) {
var id = +key.substr(key.length - 1);
if (isNaN(id)) {
updatebankdata[0] = updatebankdata[0] || {};
updatebankdata[0][key] = bankdata[key];
} else {
var uniqid=$("#bankaccount"+id).attr("uniq_id");
updatebankdata[id] = updatebankdata[id] || {};
var field = key.substring(0, key.length - 1);
updatebankdata[id][field] = bankdata[key];
updatebankdata[id]["uniquid"] = uniquid;
}
}
return updatebankdata;
}
my bank data is like
{bankname1: "new", micrcode1: "mkkk", comments1: "commentsfvfdv", bankname2: "bankfgname", micrcode2: "micrfgcode"…}
i want to change it into like this way
[{bankname1: "new", micrcode1: "mkkk", comments1:
"commentsfvfdv"},{bankname2: "bankfgname", micrcode2: "micrfgcode"}]
but still it getting like this .its not good
{"0":{bankname1: "new", micrcode1: "mkkk", comments1:
"commentsfvfdv"},"1":{bankname2: "bankfgname", micrcode2: "micrfgcode"}
what is the mistake in my code?
You need to use an array instead of an object. Like so:
function func(data) {
var bankdata = data;
var updatebankdata = []; // ARRAY instead of Object
for (var key in bankdata) {
var id = +key.substr(key.length - 1);
if (isNaN(id)) {
updatebankdata[0] = updatebankdata[0] || {};
updatebankdata[0][key] = bankdata[key];
} else {
var uniqid=$("#bankaccount"+id).attr("uniq_id");
updatebankdata[id] = updatebankdata[id] || {};
var field = key.substring(0, key.length - 1);
updatebankdata[id][field] = bankdata[key];
updatebankdata[id]["uniquid"] = uniqid; // CHANGED to "uniqid" to match variable declaration above, not the key on the left is still "uniquid"
}
}
return updatebankdata;
}
Then you can get result like:
JSON.stringify(func({name: 'someval', val: 123}));
"[{"name":"someval","val":123}]"
assign
var updatebankdata = [];
then push your object to array like this
updatebankdata.push(yourObject)

How to convert POST form data to JSON object

if there any default functions that can convert a post form data string into json object ?
Here is an example
sendNotification=true&type=extended&additionalNotes=&returnToMainPage=true
As you can this is the format of POST form data. I need to convert it into JSON object
{
"sendNotification": "true",
"type": "extended",
"additionalNotes": "",
"returnToMainPage": "true"
}
Also it should handle arrays like this
blog.blogposts[1].comments 1
blog.blogposts[1].likes 12
I wonder how can I do this using existing tools and libraries. I know that I can write my own converter, but I guess there should a default one.
Thanks
IMPORTANT
I don't have a form, I need just convert the form data string.
Try this
var params = getUrlVars('some=params&over=here');
console.log(params);
function getUrlVars(url) {
var hash;
var myJson = {};
var hashes = url.slice(url.indexOf('?') + 1).split('&');
for (var i = 0; i < hashes.length; i++) {
hash = hashes[i].split('=');
myJson[hash[0]] = hash[1];
}
return myJson;
}
I found it here Convert URL to json
I see it this way
getStringJson('sendNotification=true&type=extended&additionalNotes=&returnToMainPage=true');
function getStringJson(text) {
var json = {}, text = text.split("&");
for (let i in text){
let box = text[i].split("=");
json[box[0]] = box[1];
}
return JSON.stringify(json);
}
Output generated:
"{"sendNotification":"true","type":"extended","additionalNotes":"","returnToMainPage":"true"}"
Working Demo
// Form Data String
var dataString = "sendNotification=true&type=extended&additionalNotes=&returnToMainPage=true";
// Split the String using String.split() method. It will return the array.
var params = dataString.split("&");
// Create the destination object.
var obj = {};
// iterate the splitted String and assign the key and values into the obj.
for (var i in params) {
var keys = params[i].split("=");
obj[keys[0]] = keys[1];
}
console.log(obj); // Object {sendNotification: "true", type: "extended", additionalNotes: "", returnToMainPage: "true"}
Building on the answer from Prashanth Reddy, if you want json string output simply add JSON.stringify(myJson); on the return
var params = getUrlVars('sendNotification=true&type=extended&additionalNotes=&returnToMainPage=true');
console.log(params);
function getUrlVars(url) {
var hash;
var myJson = {};
var hashes = url.slice(url.indexOf('?') + 1).split('&');
for (var i = 0; i < hashes.length; i++) {
hash = hashes[i].split('=');
myJson[hash[0]] = hash[1];
}
return JSON.stringify(myJson);
}
Output: {"sendNotification":"true","type":"extended","additionalNotes":"","returnToMainPage":"true"}

Serialize/Reg ex

I use serialize function to get all the values of my form.
My problem is how can i extract only the value in the generated url string of the serialize function and split it into an array.
var input = $('#addForm').serialize();
deviceBrand=itemBrand&deviceModel=itemModel&deviceSerial=itemSerial&deviceType=Desktop&deviceStatus=Available&deviceDesc=item+description //generated url string
i need string function to extract each string between "=" and "&" and put each String into an array.
Don't use serialize, use serializeArray. It creates an array of objects of the form {name: "xxx", value: "yyy" } that you can process more easily.
var input = $("#addForm").serializeArray();
var values = input.map(x => x.value);
You can also make an object with all the name: value properties:
var object = {};
input.map(x => object[x.name] = x.value);
try this code to unserialize the string,
(function($){
$.unserialize = function(serializedString){
var str = decodeURI(serializedString);
var pairs = str.split('&');
var obj = {}, p, idx, val;
for (var i=0, n=pairs.length; i < n; i++) {
p = pairs[i].split('=');
idx = p[0];
if (idx.indexOf("[]") == (idx.length - 2)) {
// Eh um vetor
var ind = idx.substring(0, idx.length-2)
if (obj[ind] === undefined) {
obj[ind] = [];
}
obj[ind].push(p[1]);
}
else {
obj[idx] = p[1];
}
}
return obj;
};
})(jQuery);

Categories

Resources