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

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);

Related

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"}

Convert object from localstorage into text

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);
}

SCRIPT28: Out of stack space

Getting stack out of space in IE 10,11 when I try encode a array of data to Json and store it into an array
var SelPeriod = Ext.getCmp('SelectedPeriodGrid');
SelPerioddata = [];
var PeriodsSelected = SelPeriod.getStore('MarkettrackDrillDownPeriods').getRange();
for (var i = 0; i < PeriodsSelected.length; i++) {
SelPerioddata.push(PeriodsSelected[i]);
}
var SelPerioddatajson = [];
SelPerioddatajson = Ext.JSON.encod(SelPerioddata);
Try using only the record's data, like:
SelPerioddata.push(PeriodsSelected[i].data);
You can also rewrite this like:
var selPeriod = Ext.getCmp('SelectedPeriodGrid'),
periodsSelected = selPeriod.getStore('MarkettrackDrillDownPeriods').getRange(),
selPerioddatajson = Ext.JSON.encode(periodsSelected.map(function(record) {
return record.data;
}));

js Array undefined after json declaration

I m new a web developer and i face up the following problem:
"Cannot read property 'length' of undefined"
my code:
var data=();
for(var i;i<parseInt(window.localStorage["numOfInserts"]);i++){
data["category_name"]=localStorage.getItem(("category_name_"+i).toString());
data["category_id"]=localStorage.getItem(("category_id_"+i).toString());
data["provider_name"]=localStorage.getItem(("provider_name_"+i).toString());
data["provider_id"]=localStorage.getItem(("provider_id_"+i).toString());
data["appointment_date"]=localStorage.getItem(("appointment_date_"+i).toString());
data["appointment_time"]=localStorage.getItem(("appointment_time_"+i).toString());
}
$scope.allAppointments=dataArray;
for(var i=0;i<dataArray.length;i++){
$scope.showme[i]=false;
}
After some research I understand that the problem caused to the fact that data is an array but I try to turn it to json, but
var data ={};
gives me the same error as before.
Please Help me
I think this is what you're looking for, see code comments:
// Create an array using []
var data = [];
// Get the count once
var count = parseInt(window.localStorage["numOfInserts"]);
// Be sure to initialize `i` to 0
for (var i = 0; i < count; i++) {
// Create an object to push onto the array, using the information
// from local storage. Note that you don't need toString() here.
// Once we've created the object (the {...} bit), we push it onto
// the array
data.push({
category_name: localStorage.getItem("category_name_"+i),
category_id: localStorage.getItem("category_id_"+i),
provider_name: localStorage.getItem("provider_name_"+i),
provider_id: localStorage.getItem("provider_id_"+i),
appointment_date: localStorage.getItem("appointment_date_"+i),
appointment_time: localStorage.getItem("appointment_time_"+i)
});
}
This does the same thing, it's just more verbose and so could help you understand more clearly what's going on:
// Create an array using []
var data = [];
// Get the count once
var count = parseInt(window.localStorage["numOfInserts"]);
// Be sure to initialize `i` to 0
for (var i = 0; i < count; i++) {
// Create an object to push onto the array
var obj = {};
// Fill it in from local storage. Note that you don't need toString() here.
obj.category_name = localStorage.getItem("category_name_"+i);
obj.category_id = localStorage.getItem("category_id_"+i);
obj.provider_name = localStorage.getItem("provider_name_"+i);
obj.provider_id = localStorage.getItem("provider_id_"+i);
obj.appointment_date = localStorage.getItem("appointment_date_"+i);
obj.appointment_time = localStorage.getItem("appointment_time_"+i);
// Push the object onto the array
data.push(obj);
}
You need to create an array(dataArray before the loop), and create a new object in each iteration and set the property values for that object then add the object to the array like below
var dataArray = [],
data, numOfInserts = parseInt(window.localStorage["numOfInserts"]);
for (var i = 0; i < numOfInserts; i++) {
data = {};
data["category_name"] = localStorage.getItem(("category_name_" + i).toString());
data["category_id"] = localStorage.getItem(("category_id_" + i).toString());
data["provider_name"] = localStorage.getItem(("provider_name_" + i).toString());
data["provider_id"] = localStorage.getItem(("provider_id_" + i).toString());
data["appointment_date"] = localStorage.getItem(("appointment_date_" + i).toString());
data["appointment_time"] = localStorage.getItem(("appointment_time_" + i).toString());
dataArray.push(data)
}
$scope.allAppointments = dataArray;
for (var i = 0; i < dataArray.length; i++) {
$scope.showme[i] = false;
}
It looks like you're trying to create an associative array, so the first line should indeed be
var data = {};
The next part is fine, but then it looks like you want to enumerate the keys
for(var i=0;i<Object.keys(data).length;i++){
$scope.showme[i]=false;
}

Categories

Resources