Append JSON data into custom JQuery function - javascript

I am attempting to load some json data into a custom JQuery function. There is probably an easy solution to this by I am admittedly learning as I go. Please advise if I am just going about it the wrong way.
As of now I am just appending it into the body to ensure that I am actually finding the data properly. I was trying to use append() to add it into the function as well but was not getting any where.
$.getJSON("designs/new.json",function(result){
$.each(result, function(i, field){
$("body").append(field['hex'] + " ");
});
});
Essentially what I'd like to do is replace the hex data values for this colorPicker function with the hex codes from my json data above. I've been messing with it for a while and can't seem to find the right approach.
$.fn.colorPicker.defaults.colors = ['000', '000', 'fff', 'fff'];
I appreciate the help in advance!

Try using alert(JSON.stringify(result)) to see if your json data is loaded properly. This code should work:
$.getJSON("t.json", function (result) {
//alert(JSON.stringify(result));
$.fn.colorPicker.defaults.colors = result.colors;
});
where t.json has the following content:
{
"colors": ['00a', '00b', 'ffa', 'ffb']
}

If I understand correctly:
1) Your JSON returns an array of objects (presumably four?) that each have a "hex" property.
2) You want to set the color picker's default colors based on these four hex properties.
So, assuming that my assumptions are correct and your array is properly ordered, you could do something like this:
$.getJSON("designs/new.json",function(result){
$.fn.colorPicker.defaults.colors = $.map(result, function(i) {
return i.hex;
});
});
I've mapped the hex properties to an array and assigned it directly to the colors. Again, this is assuming you have an array of four objects in your result object, each with a hex property.

Related

Removing attributes from nested array in D3

I am trying to filter out some attributes from an array in D3. The array contains the values of a csv file.
This all worked well for a small csv file doing it like this:
d3.csv("foods.csv", function(data) {
data.forEach(function(v){ delete v.name });
data.forEach(function(v){ delete v.created_at });
});
This is what the first array looks like:
But when I try to do it for a bigger csv file I get an error saying : "devtools was disconnected from the page. once page is reloaded devtools will automatically reconnect".
This is what the 2nd array looks like.
Why is this not working for the 2nd array? Is the array too big or should I try to address the values recursively because I already tried doing it like this:
function deleteCitation(v) {
if(Object.prototype.toString.call(v) === '[object Array]' ) {
v.forEach(deleteCitation);
}
else {
delete v.citation;
}
}
d3.csv("compounds_foods.csv", function(data) {
data.forEach(deleteCitation);
print(data);
});
I never loaded an CSV with 740 thousand rows. However, I believe you have some alternatives:
Use a row conversion function, or an accessor function:
d3.csv("foods.csv", deleteCitation, function(data) {
//the rest of the code
And then declare the conversion function:
function deleteCitation(d){
delete d.name;
delete d.created_at;
return d;
}
I didn't benchmarked it, maybe the conversion function takes the same time that your forEach (they do pretty much the same thing), but I believe that it's worth to check if this is quicker than calling your deleteCitation function for each object inside the data array.
The second alternative is simpler: don't remove those two properties, just leave them there and don't use them!
When you load an CSV to your data array you don't have to use all the properties in each object for your visualisation. You can simply ignore them. It's possible that you waste more processing time manipulating that huge array than simply leaving those extra two objects there.
The third alternative is the logical one: as there is absolutely no way you're gonna use 740k objects in a dataviz, consider filtering/reducing/cropping this CSV before sending it to the client side.

DataSet Returned to JavaScript AngularJS

I need to know how to get an object by position with AngularJS, I return from WebAPI in C# a DataSet with 4 DataTable and save it in a $scope on my JS, when i do console.log($scope.data) in the Chrome Console see like the image. Now when i do console.log($scope.data[1]) in Chrome Console i get undefinided, but when i do console.log($scope.data.inputs0) i see the correct data. What is wrong? Thanks :)
There is no $scope.data[1]. It's not an array, it's an object. You can do a few things :
use a js library like "Underscore.js" and use _.findWhere($scope.data, {key : "someData"}); which will return the object at that key (this assumes you know the key name).
Loop through each set of inputs with an angular.ForEach. Ex:
angular.forEach($scope.data, function(item, key){
//Now something like $scope.data[0] is passed in essentially
});
If you don't know the name of it, you won't be able to get it. You could also remap your object $scope.data to something more descriptive or to keys of 0, 1, 2 etc. Having them listed as you do probably isn't the best way to handle this.
Finally i extract the key's names in an angular foreach and work with em.
angular.forEach($scope.dataInputs, function (value, key) {
var nombrePos = key.slice(-1); //key=inputs0 and nombrePos=0
...
});

Working with Data Attributes - Build a List & See if One Exists

I have 2 questions based on the graphic below:
How can I tell if one of the 'data-conversationmessageuserid' data attributes with a specific value exists - say 1000000003? I believe data selectors is what I need and have tried the following but its not working yet:
if($('#conversationsInBoxMessagesWrapperDIV')['data-conversationmessageuserid=1000000003']) {
// do something
}
How could I get all the 'data-conversationmessageuserid' data attributes into an array and the loop through them? I'm still playing with this code but its far from publishable. Trying to use .map
.map(function()
thankyou so much
Try:
if($('#conversationsInBoxMessagesWrapperDIV [data-conversationmessageuserid=1000000003]').length)
or
$('#conversationsInBoxMessagesWrapperDIV').find('[data-conversationmessageuserid=1000000003]') //Or children only to look at one level.
To get all the data values you could do:
var conversationmessageuserids = $('#conversationsInBoxMessagesWrapperDIV').children().map(function(){
return $(this).data('conversationmessageuserid');
}).get();
jQuery supports data attributes: http://api.jquery.com/data/
So you could do if($('#conversationsInBoxMessagesWrapperDIV').data('conversationmessageuserid') === 1000000003)

Parsing Json document. Can you explain why key giving values? Also help parse my list better?

I am teaching myself jquery and json for work. I have been making great progress, but now got myself very confused. My ultimate goal is to be able to parse json from a text file I have and then store them as javascript objects so I can do more stuff with it.
This is what I have done. I have the following data in json format (created from a java class I wrote). Please note that data.json looks like this:
{"Time": 15,
"Distance": 20,
"Position":[{"x":5,"y":10},
{"x":15,"y":20}]}
I formatted the above in this question to be easier to read by being on separate lines, but the raw file contains it all on one line.
I used the following code in a script:
$(document).ready(function(){
console.log("ready!");
$.getJSON('data.json', function(key,val)
{
alert(val.Time);
alert(val.Distance);
alert(val.Position);
});
});
But what it outputs is three "undefined" alerts. Why? My ultimate goal is to store Time, Distance, and the Position as javascript objects so I can draw them on a graph I made in html. However, I am obviously no way close to that because my alerts are not reading/parsing json objects right.
So I changed it to as follows, on a hunch:
$(document).ready(function(){
console.log("ready!");
$.getJSON('data.json', function(key,val)
{
alert(key.Time);
alert(key.Distance);
alert(key.Position);
});
});
Well, these is mostly promising in that I get the following alerts:
Alert 1 Output: 15,
Alert 2 Output: 20,
Alert 3 Output: [Object Object], [Object Object]
Okay, I am closer, but now very confused. Shouldn't the key be giving me alert output "Time", "Distance", and "Position" and val be "15", "20", and "[Object Object], [Object Object]". I thought json kind of works like a hashtable. Hmmmm.
Also, do I need to do a .each(key, val) to parse my list called Position? Because obviously Object Object is not going to help me much. I basically want to save this list Position as a javascript obj like
myList = [[5, 10], [15,20]]
Anyway, that is my thinking. I thank you for your time. I will upvote anyone who replies and helps me out. This is important to me.
Regards,
GeekyOmega
I'm not sure what you're trying to do with your function(key,val) { ... }, but this isn't how jQuery's getJSON works at all. The callback function for getJSON takes three parameters, data, textStatus and jqXHR. I suspect you will find that the data parameter is essentially the javascript object you wanted to build, except with fields 'x' and 'y' rather than each nested array. To get the data out, I'd do something like:
for (var i = 0; i < data.Position.length; i ++)
do_something_with (data.Position[i].x, data.Position[i].y);
key and val as you have them are misnamed. The first parameter to the $.getJSON() callback is the JSON object. See the API Doc example where the callback function is just passed a parameter called data.
[Object Object] is the default toString() for objects in javascript. To get the values of your object array, you can iterate data.Position and access the x and y properties of each object in the array.
Edit to respond to your comment:
You could always change the Position property in your JSON to be generated as an array of arrays instead of an array of objects.
Or, on the client side, you could do something like this:
var points = [];
$.each(data.Position, function(item) {
points.push([item.x, item.y]);
});
Re-read your key names. Words like route and travelTime appear in your code but not in your JSON.
Try this:
$(document).ready(function(){
console.log("ready!");
$.getJSON('data.json', function(key)
{
console.log(key.Time);
console.log(key.Distance);
console.log(key.Position[0]);
});
});
when you create a class user javascript,you can write var pepole={name:"smith",code:"YQ001",println:function(code,name){document.write(this.name+":"+this.code+"<br/>")}};,json is a class for javascript,but there is no method it's only attribute

Can I convert a json input to a list of objects within jquery?

I'm new to jQuery and just playing for fun. I have some code that I want to try to modify for my needs but the current js file is getting its data from google spreadsheets and then returning each item as objects. I don't use json to pass data from my server to jQuery so I'm wondering how I can convert json to objects.
The current way its doing it is(tabletop is the name of their js program that gets data from google docs):
Tabletop.init({
key: timelineConfig.key,
callback: setupTimeline,
wanted: [timelineConfig.sheetName],
postProcess: function(el){
//alert(el['photourl']);
el['timestamp'] = Date.parse(el['date']);
el['display_date'] = el['displaydate'];
el['read_more_url'] = el['readmoreurl'];
el['photo_url'] = el['photourl'];
}
});
I have added alerts all over the file and I think this is the area that gets the data and passes it on. I was thinking of trying to replace items in their object with objects from my json and see if it changes anything, but I'm unsure. Typrically I pass individual items via json,hashmaps, and lists, not sure how it works with objects or how to access objects(I simply call url's that I create for the requests, $("#user-history").load("/cooltimeline/{{ user.id }}");). But where do I start if I want to turn json data into objects?
If it helps, here's the demo of what I'm trying to do(but by having it use json data).
p.s. I'm really looking for the logic of how to complete what I'm trying to do and perhaps some ideas I'm missing so I can google them and learn.
Use use function JSON.parse(json) :) Or jQuery.parseJSON(json)
var json = '{"a":2}';
var object = JSON.parse(json);
alert(object.a);
You should see alert with message: 2
I don't realy know if I understand your comment, but maybe you want just do this:
postProcess: function(el){ //here el is JSON string
el = JSON.parse(el); // now el is an object
el.timestamp = Date.parse(el.date);
el.display_date = el.displaydate;
el.read_more_url = el.readmoreurl;
el.photo_url = el.photourl;
return el;
}
Btw. you do not need to use brackets on know property names without not standard names:
el['timestamp'] === el.timestamp
It will be easier if you paste your JSON

Categories