Year as an index - javascript

I had this dictionary
"name" : {
"2016" : {
"1" : "info"
}
}
I added it to sessionStorage using json.stringfy and it worked perfectly. I then appended another dictionary to the first one:
name: {
2016: {
1: {
info: {
0: {
"question": "qs1",
"information": "info1"
},
1: {
"question": "qs12",
"information": "info2"
},
}
}
}
}
and I did the same convert to a string using json.stringfy. Then I noticed this:
name: {
0 : "2016",
1 : null,
2 : null, //until 2016
2016: {
1: {
info: {
0: {
"question": "qs1",
"information": "info1"
},
1: {
"question": "qs12",
"information": "info2"
},
}
}
}
I don't know why it's counting when the typeof tells me that it's a string, not a number. Also, I don't understand why it didn't do this with the first dictionary.
Here is the code:
(function($){
x = {
"info": {
"0": {
"question": "qs1",
"information": "info1"
},
"1": {
"question": "qs12",
"information": "info2"
},
}
}
var sesion = {};
var stringinfo;
sesion["name"]=["2016"];
sesion["name"]["2016"]=["1"];
sesion["name"]["2016"]["1"] = x;
stringinfo = json.stringfy(sesion);
console.log(sesion);
console.log(stringinfo)
}(jQuery))
Try it and tell me if using a number(string) as an index does that! How can I resolve this? Thank you.

you are confusing arrays ([]) and objects ({}). At the beginning you say:
I got this array:
"name" : {
"2016" : {
"1" : "info"
}
But this is an object.
Your question is a bit difficult to follow. But if you instantiate an empty array, and tell it that numer 2016 should have a certain value, it will fill up the rest with empty (null) values.
You want to use an object, rather than an array.
Look at your code where objects and arrays get mixed up. You want to be using an object, with the key "2016", not an array which uses numbers as indexes.
added information after reviewing supplied code
(btw I fixed spelling of 'sesion' to 'session' in explanation below)
the line:
var session = {}
makes an empty object. The line:
session["name"]=["2016"];
sets the property "name" of this object to be an array containing the only string "2016".
Now it gets interesting; you just made the name property an array, so the line
session["name"]["2016"]=["1"];
makes the compiler use the following logic; since session["name"] is an array, you probably don't mean to set a property on it when you refer to session["name"]["2016"]; the string "2016" gets coerced to a number and it puts a new array on it, containing the string "1".
At this point I must point out that your code is not running, and after fixing it the output is not like you put it in your question. What happens after is the same as before, just you put in the new array at the 1st spot your object in x.
The main problem in your code as stated before sits in mixing arrays and objects.
replace the line
session["name"]=["2016"];
for example with:
session["name"] = {}
to instantiate an object on which you can put properties such as "2016", and I am not sure what the exact objective is, but if you want to make an array under this property, do it something like:
session["name"]["2016"]=[x];

Related

Stringify and parse complex object with nested arrays from localStorage

I have a very complex dictionary object consisting of very deeply nested combinations of objects and arrays.
I use a custom deepCopyObject function to make a deep copy of my object throughout my code. That works fine, I'm only including it because it's the only way I'm able to copy the object without a shallow reference.
The issue comes when I try to store and retrieve it from localStorage with parse and stringify. The below code returns:
nextQuestion local_user_dict is [object Object]
test.html:1 Uncaught SyntaxError: Unexpected token o in JSON at position 1
The code below was structured by copying the object from the console in the browser and editing the keys/values. I left all of the structure intact including the "null" values which I didn't include but I assume is due to it being an array nested within the object.
I'm told that stringify and parse should work with deeply nested and complex objects including with arrays (Though I've read elsewhere online that's not true). How can I correctly pass this object and retrieve it from localStorage?
If I use my deep copy function on the object it works fine and displays as it should, the problem only occurs when stringifying and parsing from localStorage.
var test_dict = {
"questions": {
"obj1": {
"words": [
null,
{
"test1": {
"test2": "test7",
"test3": "test6"
},
"test4": "test5"
},
{
"test8": {
"test9": 0,
"test10": "2",
},
"test11": [
null,
{
"test12": {
"no": 0,
"yes": 1
},
"test13": "test14"
},
{
"test15": {
"no": 0,
"yes": 1
},
"test16": "test17"
},
{
"test18": {
"no": 0,
"yes": 1
},
"test19": "test20"
}
]
}
]
}
}
}
localStorage.setItem('user_dict', deepCopyObject(test_dict))
let local_user_dict = localStorage.getItem('user_dict')
console.log('nextQuestion local_user_dict is ', local_user_dict)
let parsed_local_user_dict = JSON.parse(local_user_dict)
console.log('nextQuestion parsed_local_user_dict is ', parsed_local_user_dict)
user_dict = deepCopyObject(parsed_local_user_dict)
console.log('nextQuestion user_dict is ', user_dict)
function deepCopyObject(inObject) {
let outObject, value, key
if (typeof inObject !== "object" || inObject === null) {
return inObject
}
outObject = Array.isArray(inObject) ? [] : {}
for (key in inObject) {
value = inObject[key]
outObject[key] = deepCopyObject(value)
}
return outObject
}
localstorage stores strings. not objects.
change
localStorage.setItem('user_dict', deepCopyObject(test_dict))
to
localStorage.setItem('user_dict', JSON.stringify(test_dict))
and ditch the copy. you can actually use JSON parse and stringify to copy objects.

How to access the right json value that is located through an array?

I'm currently using the fixture file to make sure it will be easier to call the right value.
cy.fixture('latestLead.json').then(function (lead) {
this.lead = lead
})
My son file is the following:
{
"status": 0,
"result": {
"totalSize": 1,
"done": true,
"records": [
{
"attributes": {
"type": "Lead",
"url": "/services/data/v51.0/sobjects/Lead/111111111"
},
"Id": "111111111",
"Name": "Andres Latest Test"
}
]
}
}
The way that I'm trying to get the right value is the following:
cy.get(".gLFyf").type(this.lead.result.records.Id)
I'm able to get totalSize or done from the result object, but I'm not able to get any other value higher than that object. How can I get the Id value from the records Array?
You can access an array item (in your case it's the object) using the index position (in your case it's zero)
cy.get(".gLFyf").type(this.lead.result.records[0].Id)
try this
cy.get(".gLFyf").type(this.lead.result.records[0].Id)

Code by Zapier to loop through an array of objects, pulling out one value per object and then average those values

Using JavaScript for Zapier, I am trying to calculate the average value of a property from an array of object.
Here is one of the objects...
{
"code": 0,
"data": [
{
"id": "28737",
"owner": "1",
"date": "1581945706",
"dla": "0",
"dlm": "1582551517",
"system_source": "3",
"source_location": null,
"ip_addy": null,
"ip_addy_display": null,
"import_id": "0",
"contact_cat": "*/*",
"bulk_mail": "1",
"bulk_sms": "0",
"bindex": "76",
"f1849": "9898983",
"f1850": "Foundation Course 2: Lecture 1 QUIZ",
"f1851": "0",
"f1853": "John Doe",
"f1854": "TRUE",
"f1855": "93", // <= calculate average for this property
"f1859": "292",
"f1862": "0",
"f1867": "Kajabi",
"f1868": "0",
"unique_id": "7WB77PT"
},
...
]
}
I need to pull out the value for the property named f1855 for each object, then calculate the average and return that value via POST.
I don't think this is hard to do with JavaScript but I am not used to the rules and limits of Zapier.
Any help appreciated!
**Seeing the edited version of your post, I am now not sure if your input data is the data array inside the example or it is an array of those objects. If the second, then I don't know if you want an average for each object's data prop. or something else. But the code below could be part of the solution in either case.
I don't know anything about Zapier, but the JavaScript part could look something like this:
const inputData = //your array of objects
const reducer = (sum, theObject) => sum + parseFloat(theObject.f1855)
const sumF1855 = inputData.reduce(reducer, 0)
const avgF1855 = sumF1855 / inputData.length
This code does not handle error conditions (like if on of the objects were missing the f1855 property or divide by zero if inputData were empty). Hopefully it gives you an idea to get started.

How to acces to the data from several json objects inside an array position

I'm making a little app in nodejs, I'm struggling trying to print some data provenient from a json which has the following structure:
{
"courses": [
{
"java": [
{ "attendees": 43 },
{ "subject": "Crash course" }
]
},
{
"python":
{
"occurrences": [
{ "attendees": 24 },
{ "subject": "another crash course" },
{ "notes": "completed with issues" }
,
{ "attendees": 30 },
{ "subject": "another crash course" },
{ "notes": "completed with issues" }
]
}
}
],
}
If I want to print the attendees at 'java' I do:
console.log(myJSON.courses[0]['java'][0]['attendees']);
which prints
43
and if I want to print the notes of the 2nd occurrence of the python course I do:
console.log(myJSON.courses[1]['python']['occurrences'][2]['notes']);
which prints:
completed with issues
The before mentioned cases are correct, but what I want to do is to print the keys of 'java' ('attendees' and 'subject'), as you can see Java is an array and in its unique position it has two json objects, I've tried with:
console.log(myJSON.courses[0]['java'][0].keys;
and with
console.log(myJSON.courses[0]['java'].keys;
but they print "undefined" and "[Function: keys]" respectively.
What I'm missing here?
Could anybody help me please?:(
myJSON.courses[0]['java'] is an array with indexes. Where each index holds an object with keys. Your array doesn't exactly have the keys you want (the keys of an array are its indexes: 0, 1 etc...)
Instead, you want to access all the keys from the objects in the myJSON.courses[0]['java'] array.
You can do this by using .map and Object.keys. .map will allow you to get and convert every object in your myJSON.courses[0]['java'] array. Object.keys() will allow you to get an array of keys from the given object (in your case your array will be of length 1, and so you can access index 0 of this array).
const myJSON = {courses:[{java:[{attendees:43},{subject:"Crash course"}]},{python:{occurrences:[{attendees:24},{subject:"another crash course"},{notes:"completed with issues"},{attendees:30},{subject:"another crash course"},{notes:"completed with issues"}]}}]};
const myKeys = myJSON.courses[0]['java'].map(obj => Object.keys(obj)[0]);
console.log(myKeys);
If you have multiple keys in your objects within an array, you can also use .flatMap (take note of browser support):
const myJSON = {courses:[{java:[{attendees:43},{subject:"Crash course"}]},{python:{occurrences:[{attendees:24},{subject:"another crash course"},{notes:"completed with issues"},{attendees:30},{subject:"another crash course"},{notes:"completed with issues"}]}}]};
const myKeys = myJSON.courses[0]['java'].flatMap(Object.keys);
console.log(myKeys);

Parse JSON with jQuery

I am trying to parse the following JSON with jQuery and get each id value. Can anyone advise?
[
{
"id": "1",
"name": "Boat"
},
{
"id": "2",
"name": "Cable"
}
]
So far I have:
$.each(test, function(i,item){
alert(item);
});
But that simply lists every value. How can I
That'll list every object in your array, to get the id property of the one you're on, just add .id like this:
$.each(test, function(i,item){
alert(item.id);
});
If test is a string containing JSON, you can parse it with jQuery.parseJSON, which will return a JavaScript object.
If test is written like this:
var test = [
{
"id": "1",
"name": "Boat"
},
{
"id": "2",
"name": "Cable"
}
];
...it already is a JavaScript object; specifically an array. jQuery.each will loop through each array entry. If you want to loop through the properties of those entries as well, you can use a second loop:
$.each(test, function(outerKey, outerValue) {
// At this level, outerKey is the key (index, mostly) in the
// outer array, so 0 or 1 in your case. outerValue is the
// object assigned to that array entry.
$.each(outerValue, function(innerKey, innerValue) {
// At this level, innerKey is the property name in the object,
// and innerValue is the property's value
});
});
Live example

Categories