Filtering and rearranging model/content in Ember Controllers - json

Let's say I have a JSON array of data, something like:
[ {"name":"parijat","age":28},
{"name":"paul","age":28},
{"name":"steven","age"27},
...
]
that is part of my model, and this model is setup like this:
App.UserRoute = Ember.Route.extend({
model:function(){
return App.User.FIXTURES ; // defined above
}
});
I want to get the unique ages from this JSON array and display them in my template, so I reference the computed properties article and read up a little on how to enumerate Ember Enumerables, to eventually get this:
App.UserController = Ember.ArrayController.extend({
ages:function(){
var data = this.get('content');
var ages = data.filter(function(item){
return item.age;
});
}.property('content');
});
Now the above piece of code for controller is not correct but the problem is that it doesn't even go into data.filter() method if I add a console.log statements inside. IMO, it should typically be console logging as many times as there exist a App.Users.FIXTURE. I tried using property('content.#each') which did not work either. Nor did changing this.get('content') to this.get('content.#each') or this.get('content.#each').toArray() {spat an error}.
Not sure what to do here or what I am completely missing.

Filter is used for reducing the number of items, not for mapping.
You can use data.mapBy('age') to get an array of your ages:
ages:function(){
return this.get('content').mapBy('age');
}.property('content.#each')
or in your handlebars function you can just use the each helper:
{{#each item in controller}}
{{item.age}}
{{/each}}

Related

Implement CSV download using current filters and sort

I need to implement a download feature. It will read the data in the react-data-grid (adazzle), respecting the current columns, filters and sort, and create an array json (or comma separated strings) I can then pass to the react-csv module.
I have a data structure populated from the backend but it is not filtered nor sorted. I need to be able to ask the grid for it's data on a row-by-row basis. Can anyone point me in the right direction?
Without code or some context, I can't answer with certainty...
You supply the rowGetter prop with the collection to display, or the method to get the rows to display...I'm thinking if you filtering, then most likely you've got some sort of mechanism supporting that... Either way, you can use this property's value somehow to get exactly what you see in the grid.
If you literally want to interrogate the grid, you could try adding a reference to the grid, and then see if you can ask it for the row data. I can't remember with certainty that I saw a rows prop in the grids available props via the ref, but I imagine you should be able to (**,)
...
handleExport = async => {
const exportRows = rows;
// const exportRows = getRows(initialRows, filters);
// const exportRows = this.state.gridref.CurrentRows DISCLAIMER:CurrentRows is just for giving the idea... check out the ref yourself to see if it's possible to get the rows via the grid refs props.
downloadCSV( exportRows )
}
...
<ReactDataGrid
ref={input => {this.state.gridref = input}}
columns={columns}
rowGetter={i => rows[i]} // or maybe rowGetter={i => getRows(initialRows, filters)[i]}
rowsCount={rows.length}
onGridSort={(sortColumn, sortDirection) =>
setRows(sortRows(initialRows, sortColumn, sortDirection))
}
/>
I've only ever [set / initialised] the this.state.gridRef prop in my constructor, but I guess you could also [set / initialise] it in your componentDidMount as well...
initialise like this:
this.state.gridRef = React.createRef()

How can I get access to multiple values of nested JSON object?

I try to access to my data json file:
[{"id":1,"name":"Maria","project":[{"id":5,"name":"Animals"},{"id":6,"name":"Cats"}]}
This is my approach:
data[0].name;
But like this I get only the result:
Animals
But I would need the result:
Animals, Cats
You are accessing only the name property of 0th index of project array.
To access all object at a time you need to loop over the array.
You can use Array.map for this.
var data = [{"id":1,"name":"Maria","project":[{"id":5,"name":"Animals"},{"id":6,"name":"Cats"}]}]
var out = data[0].project.map(project => project.name).toString()
console.log(out)
If that's your actual data object, then data[0].name would give you "Maria". If I'm reading this right, though, you want to get all the names from the project array. You can use Array.map to do it fairly easily. Note the use of an ES6 arrow function to quickly and easily take in the object and return its name.
var bigObject = [{"id":1,"name":"Maria","project":[{"id":5,"name":"Animals"},{"id":6,"name":"Cats"}]}];
var smallObject = [{"id":5,"name":"Animals"},{"id":6,"name":"Cats"}];
console.log("Getting the names from the full array/data structure: "+bigObject[0].project.map(obj => obj.name))
console.log("Getting the names from just the project array: "+smallObject.map(obj => obj.name))
EDIT: As per your comment on the other answer, you said you needed to use the solution in this function:
"render": function (data, type, row) {if(Array.isArray(data)){return data.name;}}
To achieve this, it looks like you should use my bottom solution of the first snippet like so:
var data = [{"id":5,"name":"Animals"},{"id":6,"name":"Cats"}];
function render(data, type, row){
if(Array.isArray(data)){
return data.map(obj => obj.name);
}
};
console.log("Render returns \""+render(data)+"\" as an array.");

Vuejs changes order of json_encoded array, when decodes it back from props in vuejs component

Php:
$json_string = "{
"26":{"blabla":123,"group_id":1,"from":"27.08.2018","to":"02.09.2018"},
"25":{"blabla":124,"group_id":1,"from":"20.08.2018","to":"26.08.2018"},
"24":{"blabla":125,"group_id":1,"from":"20.08.2018","to":"26.08.2018"}
}"
my.blade.php template:
<my-component :records={{ $json_string }}></my-component>
MyComponent.vue:
export default {
props: ['records'],
...
mounted: function () {
console.log(this.records);
}
Output is:
{__ob__: Observer}
24:(...)
25:(...)
26:(...)
And when I use v-for, records in my table in wrong order (like in console.log output).
What I am doing wrong?
EDIT:
I figured out 1 thing:
When I do json_encode on collection where indexes are from 0 till x, than json string is: [{some data}, {some data}]
But if I do ->get()->keyBy('id') (laravel) and than json_encode, json string is:
{ "26":{some data}, "25":{some data}, "24":{some data} }
Then how I understood, issue is in different outer brackets.
In Javascript keys of objects have no order. If you need a specific order then use arrays.
Here is documentation for keyBy Laravel method: https://laravel.com/docs/5.6/collections#method-keyby
I wanted to have ids for rows data to fast and easy access without iterating over all rows and check if there is somewhere key Id which is equals with my particular Id.
Solution: not to use keyBy method in Laravel and pass json string to Vue component like following [{some data}, {some data}] (as I described in my Question Edit section) - this will remain array order as it used to be.
I found this short and elegant way how to do this, instead of writing js function by myself:
Its find() method: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find
Example:
let row = records.find( record => record.id === idToFind );

Select/isolate in multimodel approach

In API reference described methods to select/isolate objects (in condition that only one model is loaded in viewer):
- select(dbids,selectionType)
- isolate(node)/isolateById(dbids) // that is the difference?
I know select analog for multimodel:
viewer.impl.selector.setSelection([objectIds], model);
Questions are:
Is isolate analog for multimodel mode exists?
How can I select/isolate two objects from diffrenent models at once?
In the recent version of the API the viewer.impl.visibilityManager is returning a MultiModelVisibilityManager, so you can pass a model as second argument:
MultiModelVisibilityManager.prototype.isolate = function (node, model)
Take a look in viewer3D.js (L#17825) to see available methods on that object.
As far as I know there is no way to select two objects from different models in a single call, you would just issue one select call for each model passing respective ids. I don't see a problem with that.
Hope that helps.
For the isolate, you can do something like this(borrowed from the Viewer3D.js):
// Get selected elements from each loaded models
var selection = this.viewer.getAggregateSelection();
var allModels = this.viewer.impl.modelQueue().getModels().concat(); // shallow copy
// Isolate selected nodes.
selection.forEach(function(singleRes){
singleRes.model.visibilityManager.isolate(singleRes.selection);
var indx = allModels.indexOf(singleRes.model);
if (indx >= 0) {
allModels.splice(indx, 1);
}
});
// Hide nodes from all other models
while (allModels.length) {
allModels.pop().visibilityManager.setAllVisibility(false);
}
this.viewer.clearSelection();
For the select, you need to pass corresponding model and dbIds to the viewer.impl.selector.setSelection([dbIds], model); and call setSelection for each set, such as below. It cannot be archived at once.
var selSet = [
{
selection: [1234, 5621],
model: model1
},
{
selection: [12, 758],
model: model2
},
];
selSet.forEach(funciton(sel) {
viewer.impl.selector.setSelection(sel.selection, sel.model);
});

How to parse the external json in gulp-jade?

I'm using jade templates for my templating system, passing a json file in as the jade locals via my gulpfile.js, but I can't seem to deep dive into the json. I feel like I'm overlooking something basic, but can't find an example online anywhere.
gulpfile.js:
Passes the json file into jade
gulp.task('html', function() {
gulp.src('./markup/*.jade')
.pipe(jade({
pretty: true,
locals: JSON.parse( fs.readFileSync('./markup/data/website_data.json', { encoding: 'utf8' }) )
}).on('error', gutil.log))
.pipe(gulp.dest('../'))
});
Then in my jade, I just pass the locals into a variable for the sake of readability.
- var employees = locals
And I can loop through json that is one level deep:
jade:
for employee in employees
if employee.Tier === 'Founder'
li
button(data-bio="#{employee.LastName.toLowerCase()}")
img(src="/public/img/employees/#{employee.FirstName.toLowerCase()}-#{employee.LastName.toLowerCase()}.jpg", alt="#{employee.FirstName} #{employee.LastName} | #{employee.Title}")
strong #{employee.FirstName} #{employee.LastName}
| #{employee.Title}
json:
[
{
"FirstName":"John",
"LastName":"Doe",
"Title":"Strategist",
"Tier":"Founder",
"Description":"",
"Email":"",
"Links":""
},
...
]
But that has only worked for me if the items I loop through are in the root, as soon as I make the json one level deeper, I can't get it to work based on the key. I want to make the json deeper so I can different sections of a site in it instead of just the employees.
[{
"employees": [
{
"FirstName":"Jason",
"LastName":"Bellinger",
"Title":"Lorem Ipsum",
"Tier":"",
"Description":"",
"Email":"",
"Links":""
},
...
]
}]
I tried a few different approaches to to dig into the json and have failed thus far.
ATTEMPT 1: adjust the variable call and keep the same loop
- var employees = locals.employees
And I get 'Cannot read property 'length' of undefined' in the terminal running $gulp watch
Also try:
- var employees = locals['employees']
to the same result.
ATTEMPT 2: don't use the var and call locals directly in my loop
for employee in locals.employees
AND
for employee in locals["employees"]
And I end up with the same error.
ATTEMPT 3:
keep the var and adjust the loop
- var employees = locals
...
for employee in employees
li #{employee.LastName}
Then I don't get an error in Terminal, but I don't get any content. It produces one empty li.
So then, I try to go a layer deeper in the loop with:
for employee in employees[0]
li #{employee.LastName}
AND
for employee in employees['employees']
li #{employee.LastName}
AND I still get no error and one empty li
I've parsed enough json in my day and jade seems simple enough, I have to be overlooking something basic. Someone please humble me.
I also dabbled in gulp-data, but I'm getting the data into jade with my approach, so I think it's my approach in jade...
You need to access the array inside you locals variable.
The length of local = 1 and that is the entire array of employees.
You'll need to set employees = to the array inside of the locals variable with:
"- var employees = locals[0].employees"
I knew it was something basic. I reverted everything back to the original setup and changed the var and this is working.
- var employees = locals[0]['employees']
Truth be told, I thought I already tried this, but went back and tried again...