Pulling object properties out of arrays and converting to string - arrays

I am currently working on a chat app and am stuck on getting properties out of an array of objects. I first sent an ajax request with json as the datatype. When I check my (data) parameter in my success function in the console it shows an Array called results which has 9 objects each with 4 properties in them. It looks like this, except each has a different id and text etc.
results: Array[10]
0: Object
createdAt: "2013-05-22T00:41:24.394Z"
objectId: "2tzXVBpwQA"
text: "SYSTEM: I'll be back."
updatedAt: "2013-05
I want to just pull out text: for each of the objects, however I have no clue how to do this. I've searched and used many methods like $grep and for statements to get text out to no avail(I am new to programming)
Here is the sample code
function newFetch(newDisplay){
$.ajax({
url: 'https://api.parse.com/1/classes/chats',
data: null,
success: function(data){
/*alert('Load was performed.');*/
var text = $.grep(data, function(e) { return e.text == text});
newFetch(newDisplay(text));
}
,
dataType:"json"
});
};
NewDisplay in the callback is another function that appends the passed parameter to one of my .divs.
This code snippet so far seems to no grab the text but instead returns just [] when I use console. Any help is appreciated!

JSON.prase is your friend
success: function(data){
//...other success code you might want to run..
var newObjArray = {};
for (var i=0; i<data.length; i++) {
newObjArray[i] = JSON.parse(data[i]);
}
}
this should turn each entry in your array to an objects as well.
JSON.Parse on MDN

Related

Async array without using anything async?

It drives me crazy. I have a really simple "problem" and it took me hours and still have no idea whats going on.
I have a child service which inherits from a parent service (I'm using ES6). The constructor takes an 1 argument called options. options will be assigned to this._defaults.
Now before I pass the options into my object (new Service(options)) I populate options with some data. To keep it simple, my current options object looks like this:
const options = {
types: []
}
Now I add some stuff into the types array, like this:
const Types = {
standard: {
some: 'data'
},
freeroll: {
some: 'data'
},
mainevent: {
some: 'data'
},
qualifier: {
some: 'data'
}
};
angular.forEach(Types, (val, key) => {
options.types[key] = true;
});
I assign my service to the scope like this:
$scope.service = new Service(options)
and output the service using console. The console now says the value of _defaults.types is Array(0). When I click on the array the correct values will be shown but the scope is not aware of that.
How is that? Doesn't Array(0) mean that at the time of the console.log() the array wasn't filled with any values but has been later? Like an async function would do?
Here is a plunk of my problem.
The problem is that types is an array and you're treating it like a plain Object. You can solve this one of two ways.
First just change types to an Object:
const options = {
types: {}
};
Or, if you need an Array, change how you're adding items to the array:
angular.forEach(Types, (val, key) => {
options.types.push({
type: key,
value: val
});
});
Note that this is just one way of turning the object into an array, the data structure you end up with is up to you.

Array object namespace meteor [duplicate]

This question already has answers here:
How to use Meteor methods inside of a template helper
(6 answers)
Closed 7 years ago.
it seems like i can't display an array for my namespace
{{#each reports}}
{{_id}}
{{/each}}
my code looks like this
server method.
reports : function(){
var pipeline = [
{$group:{_id: "$activity.destination.name","count":{$sum:1 } } },
{$match:{_id:{$ne:null} }}];
var result = Reports.aggregate(pipeline);
console.log(result);
return result;
from helper
reports: function(){
Meteor.call("reports",function(err, data) {
arr =[];
data.forEach(function(doc){
arr.push(doc);
});
console.log(arr);
return arr;
});
}
in the browser console, the response looks like this
[Object]
0:Object
_id: "Balance Sheet and P&L Rates - Current Year"
count: 2 ..etc
im not sure if its the namespace or its an object array of non-cursors. but it doesn't give me an error. im not sure if what im doing is correct.
Meteor.call returns immediately, and the callback is called once the data is back from the server.
Your template is referencing a helper which in turn calls the server method then immediately returns nothing at all. The helper's callback, when it returns, cannot return the data to the template.
In your case you should:
Create a collection for your reports.
Subscribe to the reports collection when visiting the page in question (this is typically done from a route controller if you're using Iron Router.
Create a publish function to publish your reports to the collection.
The last point isn't as straightforwards as usual since you're aggregating the results, but it's still possible with something like this (untested):
Meteor.publish('reports', function(options) {
var sub = this;
var pipeline = [
{$group:{_id: "$activity.destination.name","count":{$sum:1 } } },
{$match:{_id:{$ne:null} }}];
var result = Reports.aggregate(pipeline);
var arrayLength = reports.length;
for (var i = 0; i < arrayLength; i++) {
var report = reports[i];
sub.added('reports', report._id, report);
}
})
Then you can just call find on the Reports collection from your helper:
reports: function() {
return Reports.find()
}
Or else return the that same cursor as part of your data context in your Iron Router controller and use the result directly in your template.

How to call fetch method of Backbone Collection passing Id

I want to fire fetch method on Backbone Collection which would pass an Id parameter similar to what happens in Model.fetch(id)
E.g.
var someFoo= new Foo({id: '1234'});// Where Foo is a Backbone Model
someFoo.fetch();
My Backbone collection:-
var tasks = backbone.Collection.extend({
model: taskModel,
url: '/MyController/GetTasks',
initialize: function () {
return this;
}
});
In my View when I try to fetch data:-
var _dummyId = 10; //
// Tried approach 1 && It calls an api without any `id` parameter, so I get 500 (Internal Server Error).
this.collection.fetch(_dummyId);
// Tried approach 2 && which fires API call passing Id, but just after that
// I am getting error as below:- Uncaught TypeError: object is not a function
this.collection.fetch({
data: {
id: _dummyId
}
});
Found it very late : To cut short the above story I want something like Get /collection/id in backbone.
Thank you for your answers, finally I got the solution from Backbone.js collection options.
Apologies that I couldn't explain the question properly while for same requirement others have done brilliantly and smartly.
Solution : I can have something like :-
var Messages = Backbone.Collection.extend({
initialize: function(models, options) {
this.id = options.id;
},
url: function() {
return '/messages/' + this.id;
},
model: Message,
});
var collection = new Messages([], { id: 2 });
collection.fetch();
Thanks to nrabinowitz. Link to the Answer
As mentioned by Matt Ball, the question doesn't make sense: either you call fetch() on a Collection to retrieve all the Models from the Server, or you call fetch() on a Model with an ID to retrieve only this one.
Now, if for some reason you'd need to pass extra parameters to a Collection.fetch() (such as paging information), you could always add a 'data' key in your options object, and it may happen that one of this key be an id (+add option to add this fetched model rather than replace the collection with just one model)... but that would be a very round-about way of fetching a model. The expected way is to create a new Model with the id and fetch it:
this.collection = new taskCollection();
newTask = this.collection.add({id: 15002});
newTask.fetch();
In your code however, I don't see where the ID is coming from, so I am wondering what did you expect to be in the 'ID' parameter that you wanted the collection.fetch() to send?

Returning values of a fetch

Please look at the code below. It's a Backbone/Parse code that uses some underscore features.
I'm trying to iterate over an Parse class to retrieve "firstName" attributes of all objects in that class.
I have 2 issues with it.
The first one, as indicated with the comment, is that it correctly retrieves the first names, but it duplicates them. So if there are 5 objects, it will retrieve 5 firstName * 5. There is an iteration problem here. This is shown with the console log.
Second problem, is that I try to push firstName values into an array, then return it, so I can use the values later in code using the testt variable. But checking the testt content with a console log sends a message instead of the firstname lists.
Do you see anyway how to fix this code ?
var DoopizCollection = Parse.Collection.extend({
model: Subscribers
}
);
var doopizlist = new DoopizCollection();
var testt;
testt = doopizlist.fetch({
success: function(doopizlist) {
var results = [];
doopizlist.each(function(object) {
results.push(doopizlist.pluck('firstName'));
console.log(doopizlist.pluck('firstName')); // logs 2 duplicate arrays
});
return results;
},
error: function(doopizlist, error) {
console.log("error"); // The collection could not be retrieved.
}
});
console.log(testt); // logs "a b.promise...." message instead of firstNames
The duplication issue is because you are looping over doopizlist twice, once with each and again with pluck. Pluck is just basically shorthand of the map method.
The second issue is, you are expecting testt is the resulting value, when actually it is an instance of jqXHR, which is something known as a promise. So you can use the then method to log the value of the result.
var DoopizCollection = Parse.Collection.extend({
model: Subscribers
}
);
var doopizlist = new DoopizCollection();
var testt;
testt = doopizlist.fetch({
success: function(results) {
return results.pluck('firstName');
},
error: function(results, error) {
console.log("error"); // The collection could not be retrieved.
}
});
testt.then(function(results) {
console.log(results);
});

Make a json for grid data and send to back end

I need to make a json string for grid table field list.and need to send them java back end.
I have to send
id,
name,
listOfProjects,
listOfProjects contains following list,this list may contains number of items.
prjId,
prjName
Please tell me how to create a json string ?
I tried with following code sample
var dataStr = new Object();
dataStr.id=myId;
dataStr.name="myName";
dataStr.plist = new Array();
dataStr.plist[0].prjId=1stId;
dataStr.plist[0].prjName="1stName";
dataStr.plist[1].prjId=2ndId;
dataStr.plist[1].prjName="2ndName";
dataStr.plist[2].prjId=3rdId;
dataStr.plist[2].prjName="3rdName";
var data = Ext.JSON.encode(dataStr);
Ext.Ajax.request({
url : '/E2EAT/authentication/userdetails.json',
method : "GET",
headers: {
'Content-Type': 'application/json'
},
params : 'data=' + data ,
useDefaultXhrHeader : false,
withCredentials: true,
});
I can use the code above, but I need to iterate grid
1 . Please let me know how can I iterate a grid with sencha?
2 . What's the best method to make json string and send back end?
Ext gives you two loop functions: Ext.each, and Ext.iterate for objects.
To iterate over columns of a grid, you can use the Ext.grid.Panel#columns array property, containing Columns instances. For example, in order to build a list of visible columns, you can do:
var visibleColumns = [];
Ext.each(grid.columns, function(column) {
// Only columns bound to a field (exludes actions colutions, etc.)
if (!Ext.isEmpty(column.dataIndex)) {
if (column.isVisible()) {
visibleColumns.push({
field: column.dataIndex
,label: column.text
});
}
}
});
A grid doesn't necessarily have a column for every field of the underlying store, and it can have extra columns for custom rendering, actions, numbering, selection, etc. So, you may want to iterate over the fields of the store, instead of the grid columns. In this case, we'd be working we've Ext.data.Field objects:
// Get a ref to the store's model. Stores always have models; even
// if none is specified explicitly, one is created implicitly.
var model = grid.getStore().model;
var fieldNames = [];
Ext.each(model.getFields(), function(field) {
fieldNames.push(field.name);
});
Finally, you turn your data into JSON using Ext.encode. Also, you don't have to build the URL query (params) yourself, which would give more flexibility to other parts of your code that may need to add some params:
Ext.Ajax.request({
...
params: {
data: Ext.encode(rawData)
}
});
For a POST request, you can also use the jsonData property, to save yourself the json encoding:
Ext.Ajax.request({
...
jsonData: {
data: rawData
}
});
In many cases, though, it will be preferable to use a store with an appropriately configured data proxy and writer rather than a direct AJAX request.

Resources