String to array in JS - javascript

I am grabbing an array from a p tag and it works absolutely fine, but I am unable to use it as an array.
var leaderboard = [];
leaderboard = $(".tojs").text();
console.log(leaderboard);
Output (as intended):
[["aname1",1,649,201],["aname2",2,362,171],["aname3",3,270,234],["aname4",4,233,60],["aname5",5,211,9],["aname6",6,186,101],["aname7",7,157,41]]
But the problem occurs when I try to call a value.
leaderboard[0][0]
Output:
[
How would I be able to read an array from a p tag?

The output you get from console.log is a string, not an array. Try using JSON.parse() on it before trying to access like Sergiu suggested in his comment.
var leaderboard = [];
leaderboard = JSON.parse($(".tojs").text());
console.log(leaderboard[0][0]); //should be "aname1"

Related

Accessing items in fetched data

I fetched some data using google search places API. I am able to access items in the returned data array except for the link in the photo attributions. I used the following method, which works for all the other data elements:
this.data.name, this.data.vicinity, this.data.icon etc but this.data.photos.html_attributions returns as undefined. What am I doing wrong? Please see the images below for the data structure. Thx as you assist.
In your case this.data is an array. You should access the array by index:
for example:
let firstItemName = this.data[0].name;
data[0].photos[0].html_attributions[0]
If you need the link then you might need to parse the href from <a ..
You have to put in the array index, for example:
let var1 = this.data[0].photos[0].html_attributions[0];
let var2 = this.data[1].photos[0].html_attributions[0];
let var3 = this.data[2].photos[0].html_attributions[0];
...

Parse the JSON Object with Index or position instead of keyname using Jquery?

My Existing Code and Explanation
Working Fine, But I want to Create a template like Its should read JSON Data that Having keys in any name, I am Always reading data from JSON object in 2nd Position
Now I read the JSON that passed in the argument (data) inside that using the for loop extract single object in group, after that get the data using key(Module_Name).. I know the key(Module_Name) is always present in second position only, Now its Working Fine with keyname rather i want to fetch the data using position, that also used as template in my other modules
/* render Screen Objects */
screenRenderer.displayScreens = function(data)
{
screenRenderer.renderLayout(function(cont, boo)
{
if (boo)
{
for(i=0;i<data.length;i++)
{
var buttons = "<button class='screen_button'>"+data[i].Module_Name+"</button>";
$("#screen-cont").append(buttons);
}
}
else
{
scr_cont.show();
}
})
}
This is My Requirement, kindly awaiting suggestions, answers..
Thanks in Advance
You can use the function Object.keys(obj) to get all keys of an object as array, which you can access with an Index and than use the String you get to access the property.
So it could look like this:
var obj = data[i];
var keys = Object.keys(obj);
var result = obj[keys[1]];
Hope this is what you want.

Populate Javascript Array with JSON Data

I am attempting to load a large set of JSON files into an array to be referenced later but Node keeps stating they're undefined. I have code along the lines of:
var myarray = [];
(...)
var loading_num = 001; // will be incremented in a loop to load data
myarray[loading_num] = fs.readFileSync("data/" + loading_num);
(...)
var reference_num = "001"; // the number being used to pull the appropriate record
(...)
console.log(myarray[reference_num].name); // just testing to attempt to decipher why it doesn't work, I'll actually be using the data obviously
Each JSON file does have a value named name and I have not implemented logic to load all of them yet as I am still just trying to get one to work.
Am I misunderstading something about Javascript arrays or objects? What am I doing wrong? There's a lot of files and they can vary in number so I have to load them in some similar fashion.
You should parse the file contents so the raw data is converted into JavaScript objects.
myarray[001] = JSON.parse(fs.readFileSync("data/001"));
First of all. fs.readFileSync reads arbitrary files. If you know your file is JSON and you want to convert it to js you need to parse it using JSON.parse.
Then 001 is 1 if you want it to be a string wrap it with quotes '001'
Array indices starts from 0.
var myarray = [];
myarray.push(JSON.parse(fs.readFileSync("data/001")));
console.log(myarray[0].name);
Or
var myarray = {}; // use object
myarray['001'] = JSON.parse(fs.readFileSync("data/001"));
var reference_num = "001";
console.log(myarray[reference_num].name);

matching content of a file

I´m having a problem with a javascript function.
The idea is read the content of a file with javascript. Everything is working ok, I can see the content of the file, just now I want to organize the content.
And what I meant with organize is:
My file have a lot of strings, for example: tel#01234567#tel tel#01456789#tel dept#level1#dept dept#level4#dept.....
And everything is a line of strings, and at the end is that all what I see...
My goal is, when I read the file, at the end it have to show something like this:
Tel: 01234567
01456789
Dept: Level1
Level2
There is a way to have something like that?
function loaded(evt)
{
// Obtain the read file data
var fileString = evt.target.result;
document.getElementById('output').innerHTML = fileString;
}
So basically your file has attributes and data for the respective attribute surrounded by the attribute name + #?
The easiest thing would be to have the file in a common format for data, e.q. JSON. Then you could just use the attributes from the object you get by JSON.parse();
However, if you cannot change the file structure you will have to programm something that splits your string into the desired parts and creates an object out of the attributes to work with.
For the string you presented you could do one string.split(" ") to get every attribute singled out, resulting in an array like this:
Array [ "tel#01234567#tel", "tel#01456789#tel", "dept#level1#dept", "dept#level4#dept" ]
Afterwards you can iterate over the array and string.split("#") again for each element which gives you this:
array[0].split("#");
Array [ "tel", "01234567", "tel" ]
Then you can use the first index of the array as attribute name and the second one as its data. You could put that into an object and afterwards refer from the attribute straight to the data:
var string = "tel#01234567#tel tel#01456789#tel dept#level1#dept dept#level4#dept";
var array = string.split(" ");
var dataObject = {};
for(var i in array){
var element = array[i].split("#");
if(dataObject.hasOwnProperty(element[0])){
dataObject[element[0]].push(element[1]);
}else{
dataObject[element[0]] = [element[1]];
}
}
In the end you have an object that has all the attributes as its properties and the corresponding data stored in an array for each property. With that you should be able to work right? :)
When you read the file in you could use JS split to separate the content based on the delimiters.
Check it out here: http://www.w3schools.com/jsref/jsref_split.asp

push values into an array dynamically with javascript

I'm have trouble finding a way to push values into an array dynamically. I have given the following situation:
var get_anchors= new Array('pitzel','mitzel','sizzle')
current_anchor= pics[key].anchor; //has the value 'sizzle'
get_anchors[current_anchor].push(new Array('sizzle2','sizzle3'))
Javascript fails and says get_anchors[current_anchor] is undefined
How can I make get_anchors[current_anchor] work. Or is there a different way to get this done?
The desired result should look like 'pitzel','mitzel','sizzle'['sizzle2','sizzle3]
Based on your comment it looks like you want a hash map instead of an array. You can use an object for this:
var anchors = {
'pitzel': [],
'mitzel': [],
'sizzle': []
};
Then you can do:
anchors[current_anchor].push('sizzle2', 'sizzle3');
or assuming that anchors does not have a property with the value of current_anchor, simply assign a new array:
anchors[current_anchor] = ['fooX', 'fooY'];
Of course you can populate the object dynamically as well. Have a look at Working with Objects for more information.
I'm not sure I understand what you're trying to do, but I think you're trying to insert a few elements after where another occurs. This will do the trick:
var get_anchors = [ 'pitzel', 'mitzel', 'sizzle' ];
current_anchor = get_anchors.indexOf(pics[key].anchor);
get_anchors.splice(current_anchor + 1, 0, 'sizzle2', 'sizzle3');
// get_anchors = [ 'pitzel', 'mitzel', 'sizzle', 'sizzle2', 'sizzle3' ]

Categories