How to get json data with vars in p5.js - javascript

I'm building a dictionary word definition search engine which has a #submit button and #word input. I also have a JSON dictionary(Github link). I don't know how to select what word definition to use depending on what the user types.
I have already tried putting the input.value() as a var to the json object query:
var uInVal = input.value();
document.getElementById("p1").innerHTML = words.uInVal)
Can someone help me?
My Code:
var words;
var input;
function setup() {
loadJSON("dictionary.json", gotData);
var button = select('#submit');
button.mousePressed(keyDraw);
input = select('#word');
}
function gotData(data){
words = data;
}
function keyDraw(){
document.getElementById("p1").innerHTML; //This is where the word definition should get printed
}

In the future, please try to work with a simpler example. Something like this would show your problem in a runnable example:
var jsonString = '{"x": 42, "y":100}';
var jsonObject = JSON.parse(jsonString);
This is also easier for you to work with. Now that you have this, I'd google something like "javascript get value from property name" for a ton of results.
But basically, there are two ways to get the value of a property:
var xOne = jsonObject.x;
var xTwo = jsonObject['x'];
console.log(xOne);
console.log(xTwo);
This is what you're trying to do:
var varName = 'x';
var myX = jsonObject.varName;
This won't work, because jsonObject doesn't have any field named varName. Instead, you want to access the x field. To do that, you can use bracket [] notation:
var myX = jsonObject['x'];

Related

require() not working with variable - react native

I meet a weird problem. If I set a variable direclty with a value like this "const myString = 'someWord';" that work but if I take the value from a variable like this "const myString = someVariable;", that doesn't work, and if I set the value on a conditional block that doesn't work too.
So, work:
var jsonName = 'tramwayen';
const pathex = require('../assets/JSON/' + jsonName);
var json = JSON.parse(JSON.stringify(pathex));
doesn't work:
var jsonName = variable;
const pathex = require('../assets/JSON/' + jsonName);
var json = JSON.parse(JSON.stringify(pathex));
doesn't work:
var jsonName = '';
if (condition) {
jsonName = 'tramwayen';
}
const pathex = require('../assets/JSON/' + jsonName);
var json = JSON.parse(JSON.stringify(pathex));
I really don't understand.
I have this error :
"Invalid call at line 41: require('../assets/JSON/' + jsonName2)"
Most JS bundlers cannot handle dynamic require imports. You might want to load all of the files, and put them in an object:
let data = {
tramwayen: require('../assets/JSON/tramwayen.json'),
something: require('../assets/JSON/something.json'),
// and so on
};
And use the data object to retrieve the data you need.
From what I read while doing some research, it seems impossible to made a require dynamically. In react native require should be static.
But there are some solutions to avoid this issue.
Here is mine, I put all data of my differents Json on one single json, and I dynamically choice wich part of the data I want to get.
I can also, put all the static require on an object, and choose dynamicaly wich require I want to get.
solution 1:
const id = window.currentPI;
const json = require('../assets/JSON/mainData.json');
const nbreOfPix = json[`${id}`].preData.numberOfPictures;
solution 2:
const IMAGES = {
tramwayen: require('../assets/CtrlPI/PHOTO_articles/008_02_Img.png'),
tramwayen2: require('../assets/CtrlPI/PHOTO_articles/HC002_04_Img.png')
};
getImage = (name) => {
return IMAGES[name];
};

How to capture the value of data attribute?

The javascript snippet that we have is :
Link
I would like to retrieve the value of data-test-socialmedia type. Based on that I would like to add the conditional statement to check if the data-test-socialmedia type is facebook. As we have many data attributes like this in the site.
I tried several ways and I get object as the value. But i need the actual value in this case it is facebook. Kindly help.
//first get element
var el = document.getElementsByClassName('n-contact')[0];
//get data and replace single quotes with double quotes to create valid JSON
var d = el.dataset.testSocialmedia.replace(/'/g, '"')
//parse JSON to javascript object
var parsed = JSON.parse(d, null)
//get country if type is facebook
if(parsed.options == 'facebook')
console.log(parsed.options.country)
Link
var str = document.querySelector('.n-contact').getAttribute('data-test-socialmedia').replace(/'/g,'"');
var obj = JSON.parse(str);
var result = obj.type;
console.log(result);
it would work.
With jQuery
var elementData = $(".n-contact").attr("data-test-socialmedia").replace(/'/g,'"'),
parsed = JSON.parse(elementData);
console.log(parsed);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Link

How to get the "typeof" in JavaScript for a json message

When i try to get the type of an element using the below code it works.
var bodyContent = JSON.parse(response.content);
response.content = typeof bodyContent.CompanyList.Company.Name;
Output response for above was String
Whereas if i try it in the below approach this does not work for the same JSON message. Please help
var bodyContent = JSON.parse(response.content);
var nameHolder = "CompanyList.Company.Name";
response.content = typeof bodyContent[nameHolder];
Output was undefined
That's because it's a nested object, you can't just pass a period delimited name and have it recursively drill down the tree (you'll have to implement that yourself).
It's the difference between
bodyContent["CompanyList"]["Company"]["Name"]; // former
and
bodyContent["CompanyList.Company.Name"]; // latter
There are 2 solutions for this issue.
You have to parse the nameHolder path. Reference: Accessing nested JavaScript objects with string key
or use eval but I'll not write about this since it's not a good practise.
It looks for a property called "CompanyList.Company.Name".
This works:
var bodyContent = JSON.parse(response.content);
var list = "CompanyList";
var company = "Company";
var name = "Name";
response.content = typeof bodyContent[list][company][name];

Google javascript - accessing and renaming numeric object names

I imported json data into google scripts with:
var doc = Utilities.jsonParse(txt);
I can access most of the objects like such...
var date = doc.data1.dateTime;
var playerName = doc.data1.playerName;
var playerId = doc.data1.playerID;
var teamNumber = doc.data2.personal.team;
A bunch of objects I need to access have numbers as object names...
doc.data2.personal.team.87397394.otherdata
doc.data2.personal.team.87397395.otherdata
doc.data2.personal.team.87397396.otherdata
doc.data2.personal.team.87397397.otherdata
...but when I try to read the data with...
var teamId = doc.data2.personal.team.87397394;
... I get an error "Missing ; before statement."
I tried this...
var teamId = doc.data2.personal.team[87397394];
... and get "teamId undefined" in the log.
I also tied this with the same result...
var teamId = doc.data2.personal.team[+'6803761'];
I can read in the names as strings very easily with "For In", but can't get to the objects themselves. Every example I've found so far uses the brackets so I'm stumped what to try next.
Thank you!
Brian
UPDATE
I used this per your suggestions to get the object name into a variable and using the variable in brackets. No error but var test remains "undefined"...
for(var propertyName in doc.data2.personal.team) {
// propertyName is what you want
// you can get the value like this: myObject[propertyName]
Logger.log (propertyNames);
var test = doc.data2.personal.team[propertyName];
}
The log shows the object names, as expected...
87397394
87397395
87397396
87397397
I'm thinking it's a bug in Google's implementation. Here is an example if anyone wants to verify it. test will return undefined...
function myFunction1() {
var txt = UrlFetchApp.fetch("http://www.hersheydigital.com/replays/replays_1.json").getContentText();
var doc = Utilities.jsonParse(txt);
for(var propertyName in doc.datablock_battle_result.vehicles) {
Logger.log (propertyName);
var test = doc.datablock_battle_result.vehicles[propertyName];
}
}
The problem seems to be in the Utitlies.jsonParse. The following works fine
var txt = UrlFetchApp.fetch("http://www.hersheydigital.com/replays/replays_1.json").getContentText();
var doc = JSON.parse(txt);
for(var propertyName in doc.datablock_battle_result.vehicles) {
var vehicle = doc.datablock_battle_result.vehicles[propertyName];
Logger.log('Vehicle id is ' + propertyName);
Logger.log('Vehicle value is ' + JSON.stringify(vehicle));
break;
}

Changing the selected object in Javascript

What I am trying to do is rewrite content on the page depending on which object I have selected. I have some objects like so:
function floorPlan(name,rev,sqft,bedrm,bthrm) {
this.name = name;
this.rev = rev;
this.sqft = sqft;
this.bedrm = bedrm;
this.bthrm = bthrm;
}
// 1BR Plans
var a1 = new floorPlan('A1',false,557,1,1);
var a2 = new floorPlan('A2',false,652,1,1);
var a3 = new floorPlan('A3',false,654,1,1);
var a4 = new floorPlan('A4',false,705,1,1);
var a5 = new floorPlan('A5',false,788,1,1);
// The Selected plan
var currentPlan = floorPlan.a1;
I am having the user control this via a .click() function in a menu:
$('.sideNav li').click(function() {
// Define the currentPlan
var current = $(this).attr('id');
var currentPlan = floorPlan.current;
});
The problem is that currentPlan keeps coming back as undefined and I have no idea why. Should I be defining currentPlan differently? I can't seem to find any resources to help me find the answer.
UPDATED:
I switched out a few parts per your suggestions:
// The Selected plan
var currentPlan = a1;
and....
// Define the currentPlan
var current = $(this).attr('id');
currentPlan = current;
However, everything is still returning undefined in the click function (not initially though).
First of all $('this') should be $(this)
Secondly you're trying to use a read ID from your LI as a variable name. That doesn't work. If you store your plans in an array you can use the ID to search in that array:
var plans=Array();
plans["a1"]=new floorPlan('A1',false,557,1,1);
plans["a2"]=new floorPlan('A2',false,652,1,1);
Then your jQuery code should be altered to this:
$('.sideNav li').click(function() {
// Define the currentPlan
var current = $(this).attr('id');
var currentPlan = plans[current];
alert(currentPlan);
});
I created a JSFiddle for this. Is this what you were looking for?
Use as floorPlan.currentPlan = a1;
instead of var currentPlan = floorPlan.a1;
Please create a plunker and will correct if any issue.
I spot two errors.
When you write var inside a function, that variable is only accessible with that function. Right now you are creating a new variable in your anonymous function that is "hiding" the global variable with the same name.
So, first remove the var keyword from the assignment in the anonymous function (the one you call on "click").
Secondly I think you mean to assign floorPlan[current].
The final line should read:
currentPlan = floorPlan[current];

Categories