How to count total and null values in AngularJs object - javascript

I'm trying to count total not null fields out of total fields in my angularjs object, then I want to calculate the percentage.
eg:
in my object contain 10 fields.two fields have some values(others null).
Completed = (not null fields/total fields)*100
= (4/11)*100 = 36.36%
my controller
myApp.controller('PController', function ($scope,localStorageService) {
$scope.user = localStorageService.get("user");
console.log(Object.keys($scope.user).length);
});
now i can get total fields.but how can i count not null fields and callculate percentage?
$scope.user object is like below
{
"user_id": "205",
"first_name": null,
"last_name": null,
"email": "at#yuib.com",
"address": null,
"mobile": null,
"phone": null,
"profile_img": null,
"gender": null,
"registered": "1",
"addresses": 0
}

simple filter method with Object.keys on the $scope.user should give the required result
Object.keys($scope.user).filter(x=>$scope.user[x]!==null).length

Try this:
Object.values($scope.user).filter((item) => item != null).length

Related

How to get a length of this JSON Object?

I have the following object stored in my LocalStorage, How do I get the .length of everything? I'm trying to get the total amount of records (without DT_RowID)?
This is what I'm working with:
const cartLength = Object.values(JSON.parse(localStorage.getItem('todo'))).flat().length;
console.log("JSON obj length: ", cartLength);
here is my json object (as is)
{
"15894903752910": {
"Name": "John",
"Grade": "",
"Gender": "F",
"DOB": "2013/07/10",
"DT_RowId": "15894903752910" <--- this must be excluded in the 'items' count
},
{
"15894903752911": {
"Name": "Jane",
"Grade": "",
"Gender": "F",
"DOB": "2003/07/10",
"DT_RowId": "15894903752910" <--- this must be excluded in the 'items' count
}
....
}
The result of this should be 2 records and 8 items
Very confusing question but to get a count of all the record keys, excluding DT_RowId, something like this...
const todos = JSON.parse(localStorage.getItem('todo'))
const records = Object.values(todos)
console.log('total records', records.length)
const itemLength = records.map(r => Object.keys(r).filter(k => k !== 'DT_RowId'))
.flat().length
I think you want to count the keys:
Object.keys(myObject).length
Is that what you wanted?

Get json array value from observable and give data to frontend

Trying get JSON array from json-server using observables and then giving the value to frontend and perform search on the JSON array received through observable
created a service and used HTTP get to connect to server and subscribed to it
created for loop to get value from returned value of subscription
**service.ts**
export class FormdtService {
baseul='http://localhost:3000/objects'//jsonserver url
constructor(private http:HttpClient) { }
getdt():Observable<any>{
return this.http.get(this.baseul)
}
}
**component.ts**
export class FormsComponent implements OnInit {
constructor(public fbu:FormBuilder,private fdts:FormdtService) {}
//creates the reactive form
form=this.fbu.group({
un:'',
id:''
})
// baseul='http://localhost:3000/objects/';
//ngsubmit control of form brings this function
ser(){
this.fdts.getdt().subscribe(dt=>{
console.log("data: "+dt[0])
this.formdt.push(dt)
//console.log("formdt :"+this.formdt[0])
for (let ite in this.formdt){
let ite1=JSON.parse(ite)
// console.log("ite :"+this.formdt[ite]);
//console.log("ite1"+ite1);
this.idlist.push(ite1.person.bioguideid.value)
if(ite1.person.bioguideid.stringify==this.idsearch)
this.objson=ite1
}});
}
idsearch:string
formdt:string[]
idlist:string[]
objson:JSON
ngOnInit() {
}
//this function is attached to button in frontend
ser(){
this.fdts.getdt().subscribe(dt=>
this.formdt.push(dt)//subscribes to service
for (let ite in this.formdt){
let ite1=JSON.parse(ite)
this.idlist.push(ite1.person.bioguideid.value)
if(ite1.person.bioguideid.value==this.idsearch)
this.objson=ite1
})}
**json**
[
{
"caucus": null,
"congress_numbers": [
114,
115,
116
],
"current": true,
"description": "Senior Senator for Tennessee",
"district": null,
"enddate": "2021-01-03",
"extra": {
"address": "455 Dirksen Senate Office Building Washington DC 20510",
"contact_form": "http://www.alexander.senate.gov/public/index.cfm?p=Email",
"fax": "202-228-3398",
"office": "455 Dirksen Senate Office Building",
"rss_url": "http://www.alexander.senate.gov/public/?a=rss.feed"
},
"leadership_title": null,
"party": "Republican",
"person": {
"bioguideid": "A000360",
"birthday": "1940-07-03",
"cspanid": 5,
"firstname": "Lamar",
"gender": "male",
"gender_label": "Male",
"lastname": "Alexander",
"link": "https://www.govtrack.us/congress/members/lamar_alexander/300002",
"middlename": "",
"name": "Sen. Lamar Alexander [R-TN]",
"namemod": "",
"nickname": "",
"osid": "N00009888",
"pvsid": "15691",
"sortname": "Alexander, Lamar (Sen.) [R-TN]",
"twitterid": "SenAlexander",
"youtubeid": "lamaralexander"
},
"phone": "202-224-4944",
"role_type": "senator",
"role_type_label": "Senator",
"senator_class": "class2",
"senator_class_label": "Class 2",
"senator_rank": "senior",
"senator_rank_label": "Senior",
"startdate": "2015-01-06",
"state": "TN",
"title": "Sen.",
"title_long": "Senator",
"website": "https://www.alexander.senate.gov/public"
},//end of single json array object
{
"caucus": null,
"congress_numbers": [
114,
115,
116
],
"current": true,
"description": "Senior Senator for Maine",
"district": null,....same repetition of structure
The ser function should give whole JSON array present in server to formdt[] and then iterate over it and get every object and convert to JSON and push bioguide to id array,search id from input and match with JSON nested value of each object in the array
nothing happens gives error in console :
_this.formdt is undefined at line 37 (this.fdts.getdt().subscribe(dt=>this.formdt.push=dt))
Given error is pretty explicit : this.formdt is undefined.
You've declared preperty type but haven't initialize it.
So replace formdt:string[] with formdt:string[] = []

Script that stores multiple values from JSON dictionary into array

I have over 1000s of dictionaries in JSON after an API request. How do create a script that iterates over all dictionaries and stores the values of one of the key-value pairs?
example
},"testData"
{
"testJSON": "test",
"phone": null,
"address: "122 main st"
}, "testData1"
{
"testJSON": "test1",
"phone": null,
"address: "123 main st"
},
For example, how do I get the "address" field of every single JSON dictionary?
You need to first parse your json, like this:
var json = JSON.parse(jsonString);
then you could iterate your json keys and do something with the root values, like such:
for(var el in json)
{
console.log(json[el]) // will log every root element
console.log(json[el].phone) // will log phone of each element
}
example fiddle: https://jsfiddle.net/1ky6dzen/
In python this can be done like this:
data = [{
"testJSON": "test",
"phone": null,
"address: "122 main st"
}, "testData1"
{
"testJSON": "test1",
"phone": null,
"address: "123 main st"
}]
my_array = []
for obj in data:
my_array.append(obj['address'])
print(my_array)
Hope this is what you were after :)
Use forEach loop to iterate over the keys of the object
var a={"testData":
{
"testJSON": "test",
"phone": null,
"address": "122 main st"
}, "testData1":
{
"testJSON": "test1",
"phone": null,
"address": "123 main st"
}};
Object.keys(a).forEach(e=>console.log(a[e].address))

tried to access value in object using the incorrect way

Edit
I tried to access value in object using the incorrect way, I have edited this question to stop others from making the same mistake.
Simply store that object into a variable (something like var obj = {...} and type obj.skills to get the skills array back. If you wanted to get test from the cal_strs array, you can do obj.cal_strs[0].test
<pre>
var obj =
{
"skills": [],
"languages": [],
"cal_strs": [{
"test": null,
"primary_test": null
}],
"id": 123,
"my_id": 1346,
"username": "blahblah",
"full_name": "mr blah",
"email": "blah#blah.com",
"location": "boston",
"manager": "boss",
"status": 1,
"abc_status": "here",
"s_s": "2010-06-08T23:00:00Z",
"s_e": "2010-06-13T07:00:00Z",
"n_c": "2010-07-08T07:00:00Z",
"last_here": null
}
console.log(obj.location);
console.log(obj.status);
<pre>
what you have here is a object literal, witch can be manipulated without the use of jquery, to read this object you use the dot notation to get the object value based on the key
obj.key = value
var obj =
{
"skills": [],
"languages": [],
"cal_strs": [{
"test": null,
"primary_test": null
}],
"id": 123,
"my_id": 1346,
"username": "blahblah",
"full_name": "mr blah",
"email": "blah#blah.com",
"location": "boston",
"manager": "boss",
"status": 1,
"abc_status": "here",
"s_s": "2010-06-08T23:00:00Z",
"s_e": "2010-06-13T07:00:00Z",
"n_c": "2010-07-08T07:00:00Z",
"last_here": null
}
console.log(obj.location);
console.log(obj.status);
var abc_status = obj.abc_status;//save the value to a variable
You're trying to access your json object as if it's an array. It's not. You can access your objects already since it's already a proper javascript object (it's not json). Simply store that object into a variable (something like var obj = {...} and type obj.skills to get the skills array back. If you wanted to get test from the cal_strs array, you can do obj.cal_strs[0].test.
Use underscore(_.pluck) get the specific values from the object.
Or try to define a new variable and reassign it .
var s = {
"skills": [],
"languages": [],
"cal_strs": [{
"test": null,
"primary_test": null
}],
"id": 123,
"my_id": 1346,
"username": "blahblah",
"full_name": "mr blah",
"email": "blah#blah.com",
"location": "boston",
"manager": "boss",
"status": 1,
"abc_status": "here",
"s_s": "2010-06-08T23:00:00Z",
"s_e": "2010-06-13T07:00:00Z",
"n_c": "2010-07-08T07:00:00Z",
"last_here": null,
}
var t = {};
t['location'] = s.location;
t['status'] = s.status;
t['abc_status'] = s.abc_status;
t['s_s'] = s.s_s;
t['s_e'] = s.s_e;
t['n_c'] = s.n_c;
in case multiple arrays use underscore.

Values from a JSON response in ajax returning as undefined

I'm having some problems when trying to retrieve values from a JSON response sent via the $.post() method in jQuery. Here is the script:
var clickedName = $('#customerId').val();
$.post("/customer-search", { name: clickedName }).done( function(response) {
var results = $.parseJSON(response);
console.log(results);
$('#account-name').html(results.firstname + ' ' + results.lastname);
$('#email').html(results.email);
$('#telephone').html(results.telephone);
if (results.fax) {
$('#fax').html(results.fax);
} else {
$('#fax').html('n/a');
}
$('#personal').fadeIn();
return false;
});
Just to explain, I'm using twitter typeahead in a Symfony2 project, and basically this script will fire when a name is clicked (selected) from the list after typing. The customer-search URL runs a search of the database as follows:
$q = $request->request->get('name');
$em = $this->getDoctrine()->getManager();
$customer = $em->getRepository('AppBundle:Oc73Customer')->findLikeName($q);
$addresses = $em->getRepository('AppBundle:Oc73Address')->findByCustomerId($customer[0]['customerId']);
$results = array();
$results['customer'] = $customer;
$results['addresses'] = $addresses;
return new Response(json_encode($results));
Which will successfully return a Json encoded response, and the value of 'response' which is printed in the console (as per the jquery above) is:
{
"customer": [{
"firstname": "Mike",
"lastname": "Emerson",
"email": "xxxx#xxxx.co.uk",
"telephone": "01234 5678910",
"fax": null,
"password": "8e1f951c310af4c20e2cd6b68dee506ac685d7ae",
"salt": "e2b9e6ced",
"cart": null,
"wishlist": null,
"newsletter": 0,
"addressId": 84,
"customerGroupId": 1,
"ip": null,
"status": 1,
"approved": 1,
"token": null,
"dateAdded": {
"date": "2016-02-16 12:59:28.000000",
"timezone_type": 3,
"timezone": "Europe/Berlin"
},
"availCredit": null,
"customerId": 75
}],
"addresses": [{}]
}
I am trying to retrieve the customer details by using the method I always use, so to get the firstname, I use results.firstname where results is a parsed JSON string, as written in my jQuery response.
However, all I get from results.firstname is undefined, even when it clearly is defined. So, basically, I'm wondering what I am doing wrong?
Hope someone can shed some light on my problem.
The properties you're trying to access are objects in the customer array, not on the parent object itself. Assuming that the response only ever contains one customer object then you can use result.customer[0], like this:
$.post("/customer-search", { name: clickedName }).done(function(response) {
var results = $.parseJSON(response);
var customer = response.customer[0];
$('#account-name').html(customer.firstname + ' ' + customer.lastname);
$('#email').html(customer.email);
$('#telephone').html(customer.telephone);
$('#fax').html(customer.fax ? customer.fax : 'n/a');
$('#personal').fadeIn();
});
If it's possible that multiple customer objects will be returned in the array the you would need to amend your code to loop through those objects and build the HTML to display them all - without using id attributes.
I was able to access it like "results.customer[0].firstname"
var cus =
{
"customer": [{
"firstname": "Mike",
"lastname": "Emerson",
"email": "xxxx#xxxx.co.uk",
"telephone": "01234 5678910",
"fax": null,
"password": "8e1f951c310af4c20e2cd6b68dee506ac685d7ae",
"salt": "e2b9e6ced",
"cart": null,
"wishlist": null,
"newsletter": 0,
"addressId": 84,
"customerGroupId": 1,
"ip": null,
"status": 1,
"approved": 1,
"token": null,
"dateAdded": {
"date": "2016-02-16 12:59:28.000000",
"timezone_type": 3,
"timezone": "Europe/Berlin"
},
"availCredit": null,
"customerId": 75
}],
"addresses": [{}]
}
alert(cus.customer[0].firstname);

Categories

Resources