Json in sessionStorage with array of objects - javascript

Hi all I am creating a Json and adding it to Sessionstorage as follows
<script type="text/javascript">
function addMoreProducts() {
if (sessionStorage.getItem("empData") === null) {
var empInformation = {
"employees": [
{ "firstName": "John", "lastName": "Doe" },
{ "firstName": "Anna", "lastName": "Smith" },
{ "firstName": "Peter", "lastName": "Jones" }
]
}
var x = JSON.stringify(empInformation);
sessionStorage.setItem("empData", x);
}
else {
if (sessionStorage.getItem("empData") != null) {
var empInformation = {
"employees": [
{ "firstName": "John1", "lastName": "Doe1" },
{ "firstName": "Anna1", "lastName": "Smith1" },
{ "firstName": "Peter1", "lastName": "Jones1" }
]
}
var v = sessionStorage.getItem("empData").toString();
var jParse = JSON.stringify(v);
var jparse1 = JSON.stringify(empInformation);
var arrayOfObjects = [jParse, jparse1];
}
var vparse = JSON.stringify(arrayOfObjects);
var vparse1 = JSON.parse(vparse);
sessionStorage.removeItem('empData');
sessionStorage.setItem("empData", vparse);
}
}
</script>
But when I retrieve the data from sessionStorage after assigning data this is not giving me proper json format can some one help me. This is the format I am getting
"["\"{\\"employees\\":[{\\"firstName\\":\\"John\\",\\"lastName\\":\\"Doe\\"},{\\"firstName\\":\\"Anna\\",\\"lastName\\":\\"Smith\\"},{\\"firstName\\":\\"Peter\\",\\"lastName\\":\\"Jones\\"}]}\"","{\"employees\":[{\"firstName\":\"John1\",\"lastName\":\"Doe1\"},{\"firstName\":\"Anna1\",\"lastName\":\"Smith1\"},{\"firstName\":\"Peter1\",\"lastName\":\"Jones1\"}]}"]"
When I watch it in console. Also I am using restful service where my service holds a datatable as a parameter how can I pass this json object to that method as DataTable

This is actually a very wide discussed issue:
This is what is proposed by microsof in this article
If this function causes a JavaScript parser error (such as "SCRIPT1014: Invalid character"), the input text does not comply with JSON syntax. To correct the error, do one of the following:
Modify the text argument to comply with JSON syntax. For more information, see the BNF syntax notation of JSON objects.
For example, if the response is in JSONP format instead of pure JSON, try this code on the response object:
var fixedResponse = response.responseText.replace(/\\'/g, "'");
var jsonObj = JSON.parse(fixedResponse);

Related

Update properties of an object of an array

I have an array of objects and I need to update a few properties of a specific object inside the array and then run the findAndUpdateById call on it. I am trying to do this but its not updating and gives me an error of undefined name property. I guess I am not following the right procedure to update an update an object of javascript and because of this i need help.
Here is my array
let arr = [
{
"_id": "1234",
"customer": {
"firstName": "John",
"lastName": "Doe",
"email": "johndoe#gmail.com",
"address": "123 Caroline Street"
}
}
]
Now I am recieving parameter like this that i need to update in my object
let ctx = {
"params": {
"changeObject": {
"firstName": "Ali",
"email": "ali#gmail.com"
}
}
}
Given: "I am getting the array of object by making .find call against id and there will be only one customer object in the received array"
// Given
let arr=[{"_id":"1234","customer":{"firstName":"John","lastName":"Doe","email":"johndoe#gmail.com","address":"123 Caroline Street"}}];
let ctx={"params":{"changeObject":{"lastName":"Ali"}}};
arr[0].customer = Object.assign(arr[0].customer, ctx.params.changeObject);
console.log(arr);
I think you were using different properties changePayload and changeObject.
You may want to use the spread operator and map for this as well.
let arr = [
{
"_id": "1234",
"customer": {
"firstName": "John",
"lastName": "Doe",
"email": "johndoe#gmail.com",
"address": "123 Caroline Street"
}
}
];
let ctx = {
"params": {
"changePayload": {
"firstName": "Ali",
"email": "ali#gmail.com"
}
}
}
arr = arr.map( data => ({
...data,
customer: {...data.customer, ...ctx.params.changePayload}
}) );
console.log( arr );
NOTE: This will change all objects in your array, but that is what you were asking for.

Convert normal array into an object

I have this normal array
["Company="Google",Country="USA",Id="123"", "Company="Volvo",Country="SWEDEN",Id="999""]
And I would like to build an object out of its values.
Expected result is
{
"root": [{
"Company": "Google",
"Country": "USA",
"Id": "123"
}, {
"Company": "Volvo",
"Country": "SWEDEN",
"Id": "999"
}
]
}
How do I work this structure in JavaScript?
the array you posted is not valid we'll need to mix single and double quotes like this:
['Company="Google",Country="USA",Id="123"', 'Company="Volvo",Country="SWEDEN",Id="999"']
if you're getting the array as a response from a request and you copied it from console than it quotes must've been escaped using \" and you don't have to fix it.
converting the array into an object:
var myArray = ['Company="Google",Country="USA",Id="123"', 'Company="Volvo",Country="SWEDEN",Id="999"']
var myObject = array2obj(myArray);
function array2obj(myArr) {
var myObj = {root:[]}
myArr.forEach(function(v) {
var currentObj = {}
v.split(",").forEach(function(vi) {
var tmp = vi.replace(/\"/g, "").split("=");
currentObj[tmp[0]] = tmp[1];
});
myObj.root.push(currentObj);
});
return myObj
}
as you can see you call the function like this var myObject = array2obj(myArray) assuming your array is stored in myArray.
now you have your object in the variable myObject:
{
"root": [
{
"Company": "Google",
"Country": "USA",
"Id": "123"
},
{
"Company": "Volvo",
"Country": "SWEDEN",
"Id": "999"
}
]
}
"reducing" the array into ids only:
as asked in comments, the following will produce a newArray = ["123", "999"]
var myArray = ['Company="Google",Country="USA",Id="123"', 'Company="Volvo",Country="SWEDEN",Id="999"'];
var newArray = myArray.map(function(x) {
var id = /,\s*id\s*=\s*"(.*?)"/gi.exec(x);
if (id) return id[1]
});
I'm using regex to match the id and .map() to create a new array with the matched results.
if you want the array to contain numbers and not strings replace return id[1] with return Number(id[1]) but you have to make sure ids are always numbers or you will get NaN errors

How to render mustache using : external json that have function as variable

I want to render mustache.js example. but I want to get data from external file.
I copy this data to "mydata.json" :
{
"beatles": [
{ "firstName": "John", "lastName": "Lennon" },
{ "firstName": "Paul", "lastName": "McCartney" },
{ "firstName": "George", "lastName": "Harrison" },
{ "firstName": "Ringo", "lastName": "Starr" }
],
"name": function () {
return this.firstName + " " + this.lastName;
}
}
I copy template to "template.html" :
{{#beatles}}
* {{name}}
{{/beatles}}
and render this files by this code :
$.get('template.html', function(template)
{
$.get('mydata.json',function(datas)
{
var rendered = Mustache.render(template, datas);
$('#content').html(rendered);
}
}
these codes not working until I remove function(s) from data file.
I tried : different 'dataType' in JQuery ajax request.
I tried : get data as text and then jQuery.parseJSON that data.
I tried : regular and LAMBDA syntax in functions scripts.
but I cant solve this problem.
I find the answer .
AJAX request datatype must be 'script' to receive data as json and function together.

Can a JSON array contain objects of different key/value pairs?

Can a JSON array contain Objects of different key/value pairs. From this tutorial, the example given for JSON array consists of Objects of the same key/value pair:
{
"example": [
{
"firstName": "John",
"lastName": "Doe"
},
{
"firstName": "Anna",
"lastName": "Smith"
},
{
"firstName": "Peter",
"lastName": "Jones"
}
]
}
If I want to change it to have different key/value pairs inside the JSON array, is the following still a valid JSON?
{
"example": [
{
"firstName": "John",
"lastName": "Doe"
},
{
"fruit": "apple"
},
{
"length": 100,
"width": 60,
"height": 30
}
]
}
Just want to confirm this. If so, how can I use JavaScript to know if the JSON "example" field contains the first homogeneous objects or the second heterogeneous objects?
You can use any structure you like. JSON is not schema based in the way XML is often used and Javascript is not statically typed.
you can convert your JSON to a JS object using JSON.parse and then just test the existence of the property
var obj = JSON.parse(jsonString);
if(typeof obj.example[0].firstName != "undefined") {
//do something
}
It doesn't matter you can mix and match as much as you want.
You could just test it
typeof someItem.example !== 'undefined' // True if `example` is defined.
It's perfectly valid JSON. Personally I prefer this syntax better, because it reads easier:
{
"example": [
{
"firstName": "John",
"lastName": "Doe"
},
{
"fruit": "apple"
},
{
"length": 100,
"width": 60,
"height": 30
}
]
}
As to answer your second question, you can read data from a JSON string by using var data = JSON.parse(datastring);. Then simply use it by calling data.property.secondlevel. Any variable can be an object, array, string or number, allowing for nested structures.
You are free to do what you want with the contents of the array. Jus remember about this before you try to iterate an access properties of each item in your array.
one thing: you won't be able to deserialize this to anything else than an array of object in your server side, so don't have surprises later.
as a hint, maybe you could include a common field in the objects specifying the "type" so later is easy to process.
var array = [{"type":"fruit", "color":"red"},
{"type":"dog", "name":"Harry"}];
var parser = {
fruit:function(f){
console.log("fruit:" + f.color);
},
dog: function(d){
console.log("dog:"+d.name);
}};
for(var i=0;i<array.length;i++){
parser[array[i].type](array[i]);
}

JSON Object to be Stored into an Array

I am currently trying to store JSON stringified objects into an array so I will be able to add new elements as I go along:
function GetAllPatients(){
var patient = null;
var patients = [];
patient = { "FirstName": "Stephanie", "Gender": "Female", "Id": "P8401", "LastName": "BARRON", "Title": "Ms", "ConsultantId": "d10", "CurrentWardAdmissionName": "Non Admitted", "DOB": "/Date(1187650800000+0100)/", "HospitalAdmissionDate": "/Date(1294848066000+0000)/", "NHSNumber": "4646399561" };
patient = { "FirstName": "Joan", "Gender": "Female", "Id": "50434619", "LastName": "SMITH", "Title": "Mrs", "ConsultantId": "d1", "CurrentWardAdmissionName": "Non Admitted", "DOB": "/Date(513039600000+0100)/", "HospitalAdmissionDate": "/Date(1332242252817+0000)/", "NHSNumber": "9999999999" };
}
and also a switch case getPatientFromStore(pid) function which will retrieve a record by pid
How would I go about achieving this?
Is there any more information which I would require to help get me closer to a solution?
Basically, I'm in the middle of creating a web application which will allow offline local storage at a disconnected state, and also sync with a database on the server.
You can insert elements into an array by using push:
For example:
patients.push({
"FirstName": "Stephanie",
"Gender": "Female",
"Id": "P8401",
"LastName": "BARRON",
"Title": "Ms",
"ConsultantId": "d10",
"CurrentWardAdmissionName": "Non Admitted",
"DOB": "/Date(1187650800000+0100)/",
"HospitalAdmissionDate": "/Date(1294848066000+0000)/",
"NHSNumber": "4646399561"
});
As far as looking up by id, rather than an array, it would be better to use an associative array, like so:
var patients = {};
function addPatient(patient) {
patients[patient.id] = patient;
}
Then in your method to return a patient given the patient's id, you can do:
function getPatient(id) {
return patients[id];
}
This is useful if you're going to be looking up patients by their id all the time.
You could also use multiple indexes to access the same patient.
E.g. if you wanted to use NHSNumber as well as id you could do the following in the addPatients() function:
var patients = { };
var nhsNumberMap = { };
function addPatient(patient) {
patients[patient.id] = patient;
nhsNumberMap[patient.NHSNumber] = patient;
}
So you could also have another function:
getPatientByNHSNumber(nhsNumber) {
return nhsNumberMap[nhsNumber];
}

Categories

Resources