JS, how to call a nameless list - javascript

I am attempting to parse and retrieve data from an API, but it seems that there is a list that has no name assigned to it, making it impossible for me to call the values within. Here is a masked and run down example of what I am referring to.
(This is the json)
{
"numberOne": [
{
(other information would be in here)
}
]
}
As you can see. number one has a list within itself, which then contains the "other information. The thing is, I cannot send a path to it in javascript (with my method) as I can't simply do convertedJson.numberOne.?.otherInformationValue
Does anyone know how something like this would be done?
Thanks :)

The name of the list in your example is numberOne.
You can access the objects in the list using their index:
exampleJSON = {
"numberOne": [
{
"num1" : "value1"
},
{
"num2" : "value2"
},
]
}
let value1 = exampleJSON.numberOne[0].num1;
let value2 = exampleJSON.numberOne[1].num2;
//...etc

Related

How to create an array and store in local storage using json

Hi guys so i have a form which takes in data like item name, code etc, so when i press the enter button...iv used json stringify and get an alert of what is stored in the local storage. However when i click reset and create a new item it just shows the new item, is there anyway i could store all my items created in local storage...? this is part of my coding. Im a beginner so please excuse if the question is too simple
Thanks
$('#myBox #EnterButton').click(function() {
ItemData = {
'ItemCode' : $('#ItemCode').val(),
'ItemName' : $('#ItemName').val()
};
localStorage.ItemData=JSON.stringify(ItemData);
$('#myBox').slideUp();
});
...
$('#myBox2 #EnterButton').click(function() {
if (localStorage.ItemData) {
alert(localStorage.ItemData);
ItemData = JSON.parse(localStorage.ItemData);
}
if (ItemData.ItemCode) {
$('#myBox #ItemCode').val(ItemData.ItemCode);
}
if (ItemData.ItemName) {
$('#myBox #ItemName').val(ItemData.ItemName);
}
})
and i have declared itemdata as a public variable. Hope its clear. TIA
You have to organize the way ÿou are using localStorage (a getter/setter class might help with maintenance). From your code above, it seems you are always overriding localStorage.ItemData with the values just inserted.
The solution would be for localStorage.Items to be an array and whenever you insert in that array, iterate over it to see if it's not already added (based on itemCode for instance) and override or insert a new item.
I presume this is enough for playing around. A more advanced concept than localStorage and used for slightly different purpuses would be pouchdb - websql in the browser.
Sounds like if you want multiple items to be stored, you should be using an array of itemData objects. You'll then have to parse this (array), and use something like Array.push(newItem) then stringify it again before saving it.
var allItems = localStorage.getItem('ItemData');
if(allItems == null) {
localStorage.setItem('ItemData', JSON.stringify([ItemData]));
} else {
allItems = JSON.parse(allItems);
allItems.push(ItemData);
localStorage.setItem('ItemData', JSON.stringify(allItems));
}

JavaScript function

I am not able to move on to the next section since i could not understand how this works. For reference I will post the link.
http://eloquentjavascript.net/1st_edition/chapter7.html
var roads = {};
function makeRoad(from, to, length) {
function addRoad(from, to) {
if (!(from in roads))
roads[from] = [];
roads[from].push({to: to, distance: length});
}
addRoad(from, to);
addRoad(to, from);
}
I am totally lost to get the basic idea of this function. Anyone who is generous to help. Thank you in advance. you are always help me to unlock many concepts.
It works by defining a function inline (addRoad) and then calling it to add a road in each direction (from to to and then to to from).
addRoad maintains a data structure of roads:
"roads": [
"fromLocation" : [ "destination1", "destination2" ],
"fromLocation2" : [ "destination3" ]
]
addRoad first checks to see if the from location exists in the array of roads (that's the if (!(from in roads)) clause. If it doesn't exist then it creates an empty array to store future destinations. It can then add the destination to that array.
To create my example data structure above I could call addRoad as follows:
addRoad('fromLocation', 'destination1');
addRoad('fromLocation', 'destination2');
addRoad('fromLocation2', 'destination3');

d3 csv readin to objects in array

I am currently trying to use the d3 framework for a university visualisation approach.
For testing purpose I want to read a csv-file and parse the rows to objects inside an array.
My csv looks like:
ID, Referred To, TimeStamp, Votes, Comment
So I want to read it with the following lines:
d3.csv("test_comments.csv", function(data) {
commentlist = data.map(function(d) {
return[+d["ID"],
+d["Referred To"],
+d["TimeStamp"],
+d["Votes"],
+d["Comment"]
]
});
});
But if I want to readout the values afterwards I am just getting "undefined"
I also tried the way mbostock described in this thread:
csv to array in d3.js
but working with a global variable is not working either.
var commentlist;
d3.csv("test_comments.csv", function(data) {
commentlist = data.map(function(d) {
return[+d["ID"],
+d["Referred To"],
+d["TimeStamp"],
+d["Votes"],
+d["Comment"]
]
});
});
console.log(commentlist);
Am I understanding something wrong?
Maybe you have a solution for me.
var commentlist=[];
d3.csv("test_comments.csv", function(data) {
commentlist=data;
});
console.log(commentlist);
What I know is, In the call back data object will contain array of JSON objects of csv file's all rows of data, that each row data is pushed as a JSON format into the data array.
As below
[{"ID": valueFromtheRow, "Referred To": value, "TimeStamp": value, "Votes":value, "Comment":value}]
The call back function is called by passing the array of JSONs.
So data object will look like
data=[{"ID": valueFromtheRow, "Referred To": value, "TimeStamp": value, "Votes":value, "Comment":value}];
Hope you understood...If not ask me.
I think the reason you got { console.log(commentlist) } undefined is that inside d3.csv the callback function is parsed and called last by browser, and { console.log(commentlist) } is called earlier even though it appears at the bottom of your code. So the moment when { console.log(commentlist) } is called, { commentlist } is actually undefined (only declared).
That being said, just try putting { console.log(commentlist) } inside the callback and it should do the job.

How do I store multiple options for a Chrome extension?

I am working on a Chrome extension that replaces words on websites with different words.
I allow users to input their own words that they would like to be replaced, and I save these like this:
function storeOptions(){
var words = new Object(); // storageArea.set() method takes an object that contains all the items to be stored. This Object contains those.
$("option").each(function(key,value){ // .each(index, element)
words[value.id] = value.text;
chrome.storage.sync.set(words, function(){console.log("Stored: "+value.text);});
});
}
Before this was implemented I was successfully enabling and disabling the extension with a browseraction that used a setting stored in the same storagearea in a similar way:
chrome.storage.sync.set({"status":"enabled"});
The problem I am facing is that after implementing the option to add words, the status either isn't being stored properly or is affected by the options, as when I try to retrieve it it doesn't have the values "enabled" or "disabled" as shown here:
chrome.storage.sync.get("status", function(result) {
console.log("status: "+result["status"]); // status: status
});
I was thinking that perhaps I could store the words to replace as an array called in a way like:
chrome.storage.sync.set({"words" : words});
And I would then be able to differentiate the two by getting "status" or "words", but that did not work.
How can I store status and the words without them interfering with each other?
The only reason for what you describe to happen is if there is an <option> element with id status and value status (in which case it would overwrite the original status).
In any case, it is (as you suggested) a good idea to "encapsulate" all option-related key-value pairs in an object (not necessarily an array) inside storage.
(Finally, there is no need to store the values one-by-one. It would be more efficient to first create the whole object and then store it with a single call to chrome.storage.sync.set().)
function storeOptions() {
const words = {};
$('option').each((idx, element) => words[element.id] = element.text);
chrome.storage.sync.set({words: words});
}
Now your storage.sync will be looking like this:
{
"status": "enabled",
"words": {
"option_id1": "option_text1",
"option_id2": "option_text2",
...
}
}
You can retrieve the values like this:
// Retrieve the extension status:
chrome.storage.sync.get('status', items => {
const status = items.status;
...
});
// Retrieve the words:
chrome.storage.sync.get('words', items => {
const words = items.words;
Object.keys(words).forEach(key => {
console.log(`Replacing '${key}' with '${words[key]}'...`);
...
});
});

JS Noob: use JavaScript 'for loop' to match a variable to a database

The title explains it pretty well, but I'm trying to build a 'for loop' that matches a variable (in this case, one garnered by an HTML5 form) to a value in a cell in a 2-column database. Then I want to 'console.log' the value in the adjacent (next column over) cell.
Looking for coding help and any suggestions for what type of database would work best with this type of arrangement.
var myDB = {AA:100, BB:50, CC:75, DD:66, EE:40};
function DB(value) {
return myDB[value];
}
console.log(DB('AA'));
It seems to be the best approach for this would be to have a data structure like this:
var myDB = {
'key1' : 'value1'
}
This would remove the need for a "for loop" as you were planning to use which is incredibly inefficient and would enable you to use a simple index check like this:
function getValue( index ) {
if( typeof myDB[index] == 'undefined' ) return false;
return myDB[index];
}
If you need to be able to search on either index, then you'll need to make a slightly more complex database layout (I'm assuming your "database" is actually just javascript data since you wanted to console.log the data.
If you're looking to do this in a server side database and return the data, you'll need AJAX functionality and server side APIs to post those ajax requests to and return your data in JSON. Which is slightly more complicated than what I just suggested above.
Update:
If you wanted to "search" the database values and find the matching key, you would probably have to either run a for loop on the myDB object, or build your database a little differently by having a separate object for each of the keys and one for the data. Something like this:
var myDB = {
'key1' : {
'value1':0,
'value2':1
},
'key2' : {
'value1':0,
'value2':1
},
'data' : {
0:'data_for_record_1',
1:'data_for_record_2'
}
}
Now you can "search" on either of the index columns and get the ID of the data row that corresponds to that matched column. This data structure is very similar to how indexes are used in most databases like MySQL and others. So your "search" function would likely look something like this:
function searchDB( index , value ) {
if( typeof myDB[index][value] == 'undefined' ) return false;
if( typeof myDB.data[myDB[index][value]] == 'undefined' ) return false;
return myDB.data[myDB[index][value]];
}

Categories