DataSet Returned to JavaScript AngularJS - javascript

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
...
});

Related

How do I get data out of JSON object withouth knowing the names

Hi I have a javascript object that looks like this:
{"_balance":"1500","texts":{
"0x4b8ca107efbc8b096c011f64d2c2d7aebdaec7fe": {"Best":"200","first one":"0"},
"0x7901b2b9caaeff5478d14873c39765373a48f890":{"number one !!!!1111":"1500"}}}
I can get objName.texts out of the object.
Which leaves me with:
{"0x4b8ca107efbc8b096c011f64d2c2d7aebdaec7fe":{"Best":"200","first one":"0"},
"0x7901b2b9caaeff5478d14873c39765373a48f890":{"number one !!!!1111":"1500"}}
It's a map of addresses with all the messages they left and the amount of points the message has. Now i need to get the messages out and sort them ascending by points but I don't know where to begin.
I'm not looking for a complete answer. Just a way to get the values out individually and put them in an array. I have no clue where to begin...
Thank you for your attention
You could use syntax like that:
Object.keys(jsonData['texts']).forEach(function(key) {
var value = jsonData['texts'][key];
console.log(key + ':');
console.log(value);
});
Please note that value is still an object, thats why I console.log it separately.
There are three handy methods that could be helpful here:
Object.keys(objName.texts) - return array of keys
Object.values(objName.texts) - return array of values
Object.entries(objName.texts) - return array of [key, value]

Updating array items angularfire

I am using angularfire $add method to add basic js objects of the form {id:integer,name:name}
Now, if I want to update a particular item (which usually has a firebase-assigned key like "-JEcA_f70efHbKi5js7j" or something, my impression is that I should use the $save method.
Here is how I am trying to do this:
$scope.chosenColors = $firebase(myChosenColorsRef);
$scope.updateColor = function(data){ //data is a JS object like {id:'id',name:'name'}
if($scope.chosenColors.$getIndex().length>0){
var keys = $scope.chosenColors.$getIndex();
keys.forEach(function(key, i) {
if($scope.chosenColors[key].id!=data.id){//if id matches I want to update name
$scope.chosenColors[key] = {id:data.id,name:data.name}
$scope.chosenColors.$save[key];
return;
}
});
}else{
$scope.chosenColors.$add(data);
}
But this doesn't appear to have any effect on the firebase...any ideas what I am doing wrong?
Firstly, you should call the $save method instead of simply accessing it with a key:
$scope.chosenColors.$save(key);
Secondly, you're iterating over all the keys to figure out which one you want to save which is pretty inefficient. You should change your updateColor argument to take the key as an argument.
<div ng-repeat="(key, color) in chosenColors">
<a ng-click="updateColor(key, color)">Update</a>
...
</div>
function updateColor(key, data) {
$scope.chosenColors[key] = data;
$scope.chosenColors.$save(key);
}
Thanks for that. I will give it a go.. the reason I am iterating over all items is I am responding to a drag event on a canvas item, and I need to know which item it is that is being dragged...I suppose I could keep that as part of the dragged object and address it directly..baby steps!
Regards,

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

Append JSON data into custom JQuery function

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.

Categories