I'm trying to implement a filter based on the answer to this question, but it isn't working for me. For code:
function MyCtrl($scope, $timeout)
{
$scope.tweets = [
{
created_at: "Date",
text: "tweet text",
users:
[
{
name: "user name",
screen_name: "user screen name",
profile_image_url: "profile pic"
},
{
name: "user name 2",
screen_name: "user screen name 2",
profile_image_url: "profile pic"
}
]
},
{
created_at: "Date",
text: "tweet text 2",
users:
[
{
name: "user name",
screen_name: "user screen name",
profile_image_url: "profile pic"
},
{
name: "user name 2",
screen_name: "user screen name 2",
profile_image_url: "profile pic"
}
]
},
{
created_at: "Date",
text: "tweet text 3",
users:
[
{
name: "user name",
screen_name: "user screen name",
profile_image_url: "profile pic"
},
{
name: "user name 2",
screen_name: "user screen name 2",
profile_image_url: "profile pic"
}
]
}
];
}
and the template:
<div ng-app ng-controller="MyCtrl">
<div ng-repeat="tweet in tweets">
for each tweet, user 2's name should be printed here >>
{{(tweet.users | filter:{screen_name:'user screen name 2'}).name}}
_____________________________________
</div>
</div>
I'm seeing output of:
for each tweet, user 2's name should be printed here >>
for each tweet, user 2's name should be printed here >>
for each tweet, user 2's name should be printed here >>
I would expect that "user name 2" would be printed out after each ">>". I don't know why that filter isn't working on an array of each iterated element. Thanks.
fiddle
The filter doesn't return a user. It returns an array of users matching the filter condition. So in that case, an array containing one user.
So it should be
{{(tweet.users | filter:{screen_name:'user screen name 2'})[0].name}}
You could have found this yourself easily by just using
{{ (tweet.users | filter:{screen_name:'user screen name 2'}) }}
to see what the result of the filter was.
AND IF THE SAME USER IS MORE THAN ONCE ON THE SAME MESSAGE?
If you have more than one message from one user, the above answer will not work and, instead, will display something strange.
In order to better filter your data, you should try to use filter functions when you have nested objects or arrays inside objects and arrays. I had a similar problem in this question: Filtering data with AngularJS Filter. How to iterate over objects?
So, to your question!
First, you need to go one level above to apply the filter to all the objects. Using the filter where you are, you can't see the big picture and act according. The tack by is being used because ng-repeat can't have duplicated values in a array.
<div ng-app='app' ng-controller="MyCtrl">
<div ng-repeat="tweet in tweets | custom track by $index">
for each tweet, user 2's name should be printed here >>
{{ tweet }}
_____________________________________
</div>
</div>
Now, this is the important part. I'm registering a angular.module as app just because I prefer this way. After that, I create a filter called custom that was acessed in the html code.
var app = angular.module('app', []);
I've changed a little your code, So I can see it better in my way:
app.controller('MyCtrl', function ($scope, $timeout){...});
app.filter('custom', function () {
return function (tweets) {
var formatted = []; //Initialize array to be returned.
for (var j = 0; j < tweets.length; j++) { //Iterate over all tweets.
var tweet = tweets[j]; //Select a single tweet.
//Above, iterate over all users on a tweet.
for (var i = 0; i < tweet.users.length; i++) {
var user = tweet.users[i]; //Select a single user of the tweet.
if (tweet.user[i].screen_name == 'user screen name 2'){
//If match what you want, insert it in the array to be returned.
formatted.push(tweet.user[i].name);
};
};
};
return formatted; //Return the array.
};
});
And, finally, if you want to test, here are a fully function jsfiddle with your own code. :)
Query is your string and filter my query like name present in json list
ng-repeat="tweet in tweets" | filter: { users: query }
Related
const book1 = this.state.books[0]; //giving one book
console.log(book1); //output->{id: 1, bookname: "Physics", price: 600, author: "ABC", pages: 567, …}
const {id,bookname,price,author,pages,category} = {book1};
console.log(price); //output->undefined
I have already tried a lot of things. How To get the value of particular property?
Here is the JSON file:
[
{
"id": 1,
"bookname": "Physics",
"price": 600,
"author": "ABC",
"pages": 567,
"category" : "Science"
}
]
The JavaScript object destructuring shown is invalid, because of the curly braces around book1.
Remove those braces:
const { id, bookname, price, author, pages, category } = book1;
Here's a simpler example:
> const book = { price: 600 }
undefined
> const { price } = book
undefined
> price
600
Yes, as Jake mentioned, what you're trying to do here is called destructuring assignment. So as per the correct syntax,
const { id, bookname, price, author, pages, category } = book1;
this would actually mean,
const id=book1.id
const bookname=book1.bookname
And so on. You could have a look at https://javascript.info/destructuring-assignment for more information on destructuring assignment.
I have this data,
[Products, Products, Products, Products]
0: Products {product_id: "1", Product_type_id: "11", Subtotal:450, …}
1: Products {product_id: "2", Product_type_id: "22", Subtotal:550, …}
2: Products {product_id: "3", Product_type_id: "33", Subtotal:600, …}
3: Products {product_id: "4", Product_type_id: "44", Subtotal:100, …}
I want to sum(Subtotal) with this function but in html show nothing
products: Products[] = [];
public cartTotal(): number {
let total: number = 0;
this.products.forEach((e: any) => {
total = total + Number(e.subtotal);
});
return total;
}
html code:
<label for="total">Totale: {{total}} </label> --> show nothing
<label for="total">{{cartTotal(total)}}Totale: ALL</label> --> show NaN
When you try to access a variable from html by {{someVar}}, angular will look at its component if an attribute called someVar exists. You are returning total from cartTotal but there is no one listening.
You have to change it to this
#Component({
selector: 'some-comp',
template: `<label for="total">Totale: {{total}} </label>`
})
export class SomeComponent {
total;
// you have to call this method at some point,
// I omitted that part. I assume you already call it.
public cartTotal(): number {
let tempTotal: number = 0;
this.products.forEach((e: any) => {
tempTotal= tempTotal+ Number(e.subtotal);
});
this.total = tempTotal;
}
}
Edit
You should not call methods directly from your markup.
<label for="total">{{cartTotal(total)}}Totale: ALL</label> which will make angular call cartTotal so many times (at every change detection cycle). You would not want to go through products array and do the calculation thousands of times.
I find a new problem,
I would like to count #NAME to set array FACET[] for show #KEY
Myjson
" RESULT":{
"FACET":[
{ "#NAME" : "creator",
"#COUNT" : "20",
"FACET_VALUES":[
{
"#KEY":"Book Company1",
"#VALUE":"13"},
{
"#KEY":"Book Company1์",
"#VALUE":"10"}],
{ "#NAME" : "lang",
"#COUNT" : "70",
"FACET_VALUES":[
{
"#KEY":"tha",
"#VALUE":"33"},
{
"#KEY":"eng",
"#VALUE":"42"}
],
{ "#NAME" : "bnb",
"#COUNT" : "64",
"FACET_VALUES":[
{
.
.
.
]
.
optionsFn(): void {
this.http.get("my_url")
.subscribe(data =>{
this.date=data.json().RESULT.FACET; //get #NAME
},error=>{
err => console.error(err),
() => console.log('getRepos completed')
);
console.log(this.date);
console.log(this.date);
this.goToapply()
}
goToapply(){
this.http.get("my_url")
.subscribe(data =>{
this.foundRepos=data.json().RESULT.FACET[0,1,2,3.4......].FACET_VALUES; ///get #KEY
},error=>{
console.log(error);
} );
}
..
<ion-label>Filterr</ion-label>
<ion-select [(ngModel)]="refine" (ionChange)="optionsFn();">
<ion-option value="..." *ngFor="let item of date">{{item["#NAME"]}},({{item["#COUNT"]}})</ion-option>
</ion-select>
<ion-list>
<ion-item *ngFor="let item of foundRepos" (click)="itemClicked($event,item)">
<h3> {{ item[#KEY"] }}</h3>
</ion-item>
</ion-list>
This value="..." I want to keep it to string for to use, but zi have know idea.
example : count #NAME = 3 (creator,lang,bnb) ,and get value="..." = 0,1,2 (0==creator ,1==lang ,2==bnb)
When I select lang I get 1 , I use this to FACET[1].FACET_VALUES , So that I get #KEY
Sorry to write wrong. My english isn't very good.
Ok. there's just a tip that I would like to point out to you. You shoud get a bit better with words. Not the English language in particular but more about explaining your current result and your desired result. I believe this will force you into learning english at a much faster pace than you're currently doing. (coming from a non-native speaker)
"I would like to count#NAME to set array FACET[] for show #KEY"
So, with the returned JSON we can do a couple of things, which do not get quite clear from immediately looking at your question (did a +1 since I don't believe it's of bad quality or isn't a good question).
So there are 3 things I should cover in my post
Counting the amount that NAME occurs
Setting an array for the FACET
Showing the KEY per FACET which seems to be the end goal.
Ok
Counting the amount that NAME occurs
So you basically already got this answer. You submitted this code
this.http.get("my_url")
.subscribe(data =>{
this.date=data.json().RESULT.FACET; //get #NAME
});
Which means you already have access to the FACET array. Counting the amount that NAME occurs can be done either by creating a for loop and checking if the name is not undefined (thus incrementing an int) or counting on the fact that NAME is always defined, thus just calling this.date.size() (if this.date is set correctly of course)
get an array for the FACET
this, you're already doing by assiging the this.date = data.json().RESULT.FACET. Your this.date now contains an array holding your FACET objects. Just see it like this: JSON (with comments which is not possible in JSON but just for demonstration purposes) =
{ FACET: // declare the main object, called FACET
[ // declaring the FACET as an Array ([] is for creating a list)
{id: 2} //initializing a child of the FACET array
,{id: 3} //initializing the second FACET child.
]
}
So, this pseudo (not realistic) JSON holds 2 objects, having id = 2 and id = 3
Ok, now you should understand a bit of JSON, let's take a look at how your code looks (taking a Businnes with multiple offices and multiple employees per office into account)
{
OFFICES" : [
{
"id" : "1",
"location" : "New York",
"employees" : [
{"id" : "1", "fullName" : "Jon Skeet"},
{"id" : "2", "fullName" : "Random Stranger"}
]
},
{
"id" : "2",
"location" : "Amsterdam",
"employees" : [
{"id" : "1", "fullName" : "Ivaro18"},
{"id" : "2", "fullName" : "Some-Random Stranger"}
]
}
]
}
This code is basically the same as your code. And the question your asking now is, taking the code from my answer, how to get all the id's or names of all the employees. (get all names of keys of facet objects)
Now let's show you in typescript
someFunction() {
this.http.get('someUrl').map(response => {
console.log(JSON.stringify(response.json())); // check what you actually retrieve
let decoded = response.json();
for(let office of decoded.OFFICE) {
console.log(office.location);
for(let employee of office.employees) {
console.log(employee.fullName);
}
}
});
}
Expected output of this program
> New York
> Jon Skeet
> Random Stranger
> Amsterdam
> Ivaro18
> Some-Random Stranger
I think this pseudo code will get you to think a bit out-of-the-box and find the answer to your question. If you can't elaborate more on what you want as output I will be glad to help you at any time (even weekends) just comment and I'll respond when I have the time!
#Ivaro18 thanks for your answers.
I want to counting the amount that #NAME
for setting an array for the FACET
and showing the KEY per FACET[] which seems to be the end goal.
Yes, you totally know what I meant.
But i want output is every #KEY of that FACET[]
Example :
<ion-select [(ngModel)]="refine" (ionChange)="optionsFn();">
<ion-option value="..." *ngFor="let item of date">{{item["#NAME"]}},({{item["#COUNT"]}})</ion-option>
</ion-select>
<ion-list>
<ion-item *ngFor="let item of foundRepos" (click)="itemClicked($event,item)">
<h3> {{ item[#KEY"] }}</h3>
</ion-item>
</ion-list>
.
optionsFn(): void {
this.http.get("my_url")
.subscribe(data =>{
this.date=data.json().RESULT.FACET; //get #NAME
},error=>{
err => console.error(err),
() => console.log('getRepos completed')
);
console.log(this.date);
console.log(this.date);
this.goToapply()
}
goToapply(){
this.http.get("my_url")
.subscribe(data =>{
this.foundRepos=data.json().RESULT.FACET[0,1,2,3.4......].FACET_VALUES; ///get #KEY
},error=>{
console.log(error);
} );
}
from above ion-select is show creator , lang and bnb ,I want to If When I select lang ion-option value="..."
to keep number of "#NAME"
example counting amount of #NAME is 3 and
when I select creator is ion-option value="..." << is 0
when I select lang is ion-option value="..." << is 1
when I select bnb is ion-option value="..." << is 2
and If i get value ,I take it to goToapply() for set FACET[]
example I select bnb I get value =2 and console.log this.refine
is show 2
take it(2) to let p = this.refine , so that p = 2
take p to this.foundRepos=data.json().RESULT.FACET[p].FACET_VALUES; for show #KEY in ion-list
When I select lang output is
> tha
> eng
new to DOJO..using JsonRest to get data from database...i have given range to display 0-1000 out of 50000 ...but it is displaying full data......requirement is that when that 1000 loaded while scrolling the next request goes to server and rest of the data will display....
please help i tried a lot ......
my code
myStore = dojo.store.Cache(dojo.store.JsonRest({
target : "myip7080/GridExample/string"
}), dojo.store.Memory());
myStore.query({
start: 0,
count: 1000
}).then(function(results){
alert(results);
});
grid = new dojox.grid.DataGrid({
store : dataStore = dojo.data.ObjectStore({
objectStore : myStore
}),
structure : [ {
name : "SNO",
field : "sno",
width : "100px",
editable : true
}, {
name : "SNAME",
field : "sname",
width : "100px",
editable : true
}, {
name : "SALARY",
field : "salary",
width : "200px",
editable : true
} ]
}, "target-node-id"); // make sure you have a target HTML element with this id
grid.startup();
dojo.query("#save").onclick(function() {
dataStore.save();
});
});
dojo/store/Memory::query() takes two parameters:
An object that queries the data
An QueryOptions object containing the options for this query (optional)
You can query specific entries from your data like this:
myStore.query(
{ name: "John Doe" }
);
//returns all rows with name="John Doe"
You don't have to make a specific query. If you want all your data, just do myStore.query("");
If you want to limit the number of rows shown, you need to add a second parameter to represent your query options:
myStore.query(
{ name: "John Doe" },
{ start: 0, count: 1000 } //return 1000 results, starting at the beginning
);
See the documentation for dojo/store/memory::query().
I have masters for Country,State.....
I made autocomplete text box for location.
This autocomplete returns all locations names from these masters(All country name and State Names).
All i passing to jquery is location names in the form of string.
I want to pass both location Id and Location Name to jquery,But want to show only location names in Autocomplete.
As this autocomplete is to used for storing preffered Location from users.
I need the id alond with respective location name to store user prefferd loaction information in user table.
Please suggest how can i do this....
A demo will be more useful.....
I assume you're using JqueryUI for autocomplete. JqueryUI's Autocomplete will, by default, work w/ json objects -- more specifically an array of object literals w/ the properties: "label" and "value";
{ label:x, value:y }
The autocomplete will use the "label" property to calculate the autocomplete match and when selected by the user, will use the "value" property as the selected item. Furthermore, if the "value" property is omitted, "label" will be used for both comparison and selection.
The important thing to note is that you're not limited to those properties. You can, for example, add additional properties such as ..say .."location_id".
{ label: "Some State and Country", location_id: 2 }
Using the autocomplete event "select", you can take some action ie store the selected location_id to a hidden input to be posted by a form or even fire a whiz-bang ajax call. Try this:
...
<form>
Locations: <input id="location" />
<input type="hidden" id="location_id" />
<input type="submit">
</form>
...
<script>
var mylocations = [
{
label: "North Carolina, USA",
id: 123
},
{
label: "North Dakota, USA",
id: 128
},
{
label: "Nevada, USA",
id: 125
},
{
label: "New York, USA",
id: 311
},
{
label: "New Brunswick, Canada",
id: 267
},
{
label: "Nova Scotia, Canada",
id: 235
},
{
label: "Newfoundlandand , Canada",
id: 223
}];
$("#location").autocomplete({
source: mylocations,
select: function( event, ui ) {
// store your location id somewhere like a hidden input ..you
// can then allow the user to post the form (and selected id) back.
$( "#location_id" ).val( ui.item.id );
return false;
}
});
</script>