Destructuring a json object in Javascript - javascript

How would access the _id and state values?
Here's the data
{
"data": {
"totalSamplesTested": "578841",
"totalConfirmedCases": 61307,
"totalActiveCases": 3627,
"discharged": 56557,
"death": 1123,
"states": [
{
"state": "Lagos",
"_id": "O3F8Nr2qg",
"confirmedCases": 20555,
"casesOnAdmission": 934,
"discharged": 19414,
"death": 207
},
{
"state": "FCT",
"_id": "QFlGp4md3y",
"confirmedCases": 5910,
"casesOnAdmission": 542,
"discharged": 5289,
"death": 79
}
]
}
}

What you have shown is a string in JSON format. You can convert that to a JavaScript object and then start to get the values you need from it.
let str = ‘{
"data": {
"totalSamplesTested": "578841",
"totalConfirmedCases": 61307,
"totalActiveCases": 3627,
"discharged": 56557,
"death": 1123,
"states": [
{
"state": "Lagos",
"_id": "O3F8Nr2qg",
"confirmedCases": 20555,
"casesOnAdmission": 934,
"discharged": 19414,
"death": 207
},
{
"state": "FCT",
"_id": "QFlGp4md3y",
"confirmedCases": 5910,
"casesOnAdmission": 542,
"discharged": 5289,
"death": 79
}
]
}
} ‘;
(Note, I have put the string in single quotes so it can be shown properly here but in your code you need to put it in back ticks so it can span many lines)
Now convert it to a JavaScript object.
let obj = JSON.parse(str);
Now look closely at the string to see how the object is structured. It actually has just one item in it, data. And that is itself an object with several items, one of which is states which is an array.
So, obj.data.states[0] is the array’s first entry. That is an object and has _id and state items.
You can step through the array extracting the ._id and .state entries.

Related

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[] = []

How to build a javascript that will return a json's objects containing specific name-value pairs

Using the below json as an example I want to write a js code that will only return the objects that contain specific name-value pairs:
Use case 1: return only the json objects containing the name-value pair "currency": "RON"
Use case 2 for nested pairs: return only the json objects containing the name-value pair "product_id": "1084929"
I want this done in plain js, not jquery.
Why would this be helpful for me? I sometimes have to validate large json files and it would help to "contract" the json to certain objects that interest me based on a specific use case.
{
"results": [
{
"currency": "RUB",
"status": "approved",
"order_id": "Y3411851",
"click_country_code": "RU",
"positions": [
{
"product_id": "1084929",
"amount": "2290.00"
}
],
"action_date": "2019-03-30 00:42:23",
"processed": 1,
"action_type": "sale",
"action": "Оплаченный заказ"
},
{
"currency": "RON",
"status": "declined",
"order_id": "Y3415290",
"click_country_code": "RO",
"positions": [
{
"product_id": "1052297",
"amount": "4390.00"
}
]
}
]
}
Try this:
Assuming that your 'results' array is inside an object called 'obj', first do:
let results = obj.results;
then,
case 1:
results.filter(obj=>obj.currency === "RON")
case 2:
results.filter(
obj =>
Array.isArray(obj.positions) &&
obj.positions.some(
position => position && position.product_id === "1084929"
)
);

How to order by multiple date time properties with nulls last?

I have a json and I want to order this json by multiple date time properties. But there is a pinnedAt property which is pointing that post has to be on top. Im using lodash by the way.
This is the sql document of what I am trying to explain:
If NULLS LAST is specified, null values sort after all non-null values; if NULLS FIRST is specified, null values sort before all non-null values. If neither is specified, the default behavior is NULLS LAST when ASC is specified or implied, and NULLS FIRST when DESC is specified (thus, the default is to act as though nulls are larger than non-nulls). When USING is specified, the default nulls ordering depends on whether the operator is a less-than or greater-than operator.
You can read more here: https://www.postgresql.org/docs/9.0/static/sql-select.html
So here is my sample data:
{
"data": [
{
"name": "Paris",
"createdAt": "2018-10-01T08:28:05.074Z",
"pinnedAt": null
},
{
"name": "New York",
"createdAt": "2018-10-01T05:16:05.074Z",
"pinnedAt": null
},
{
"name": "Washington",
"createdAt": "2018-10-02T08:28:05.074Z",
"pinnedAt": "2018-10-02T15:19:23.245Z"
}
]
}
My code to order
posts = _.orderBy(state.posts, ['pinnedAt', 'createdAt'], ['desc', 'desc']);
But this doesn't order like what I want. Here is what I expected
{
"data": [
{
"name": "Washington",
"createdAt": "2018-10-02T08:28:05.074Z",
"pinnedAt": "2018-10-02T15:19:23.245Z"
},
{
"name": "Paris",
"createdAt": "2018-10-01T08:28:05.074Z",
"pinnedAt": null
},
{
"name": "New York",
"createdAt": "2018-10-01T05:16:05.074Z",
"pinnedAt": null
}
]
}
How can I do that?
Thank you.
You can use a custom function to treat null as a different value that will sort correctly.
const data = [
{
"name": "Paris",
"createdAt": "2018-10-01T08:28:05.074Z",
"pinnedAt": null
},
{
"name": "New York",
"createdAt": "2018-10-01T05:16:05.074Z",
"pinnedAt": null
},
{
"name": "Washington",
"createdAt": "2018-10-02T08:28:05.074Z",
"pinnedAt": "2018-10-02T15:19:23.245Z"
}
];
const result = _.orderBy(data,
[(item) => item.pinnedAt ? item.pinnedAt : "", 'createdAt'],
['desc', 'desc']);
Tested using version 4.17.11 of lodash using https://npm.runkit.com/lodash
This works because the empty string is "less than" any other string value. When sorting descending, this will always show up at the end of the list. Because these empty string values are equivalent, objects without pinnedAt will be sorted based on createdAt, as expected.

jQuery Pull array from JSON response into new variable

Thank you for the help in advance. I am using a plugin which is expecting a JSON response to be an array not a object. Below is a sample of the JSON response I am getting
{
"instruments": [
{
"id": 3316,
"code": "WES",
"market_code": "ASX",
"name": "Wesfarmers Limited",
"currency_code": "AUD",
"pe_ratio": 16.38,
"nta": 4.44,
"eps": 2.55,
"current_price": 41.78,
"current_price_updated_at": "2017-10-26T16:10:09.000+11:00",
"sector_classification_name": "Retail Trade",
"industry_classification_name": "Food Retail",
"security_type": "Ordinary Shares",
"registry_name": "Computershare"
},
{
"id": 2955,
"code": "RIO",
"market_code": "ASX",
"name": "Rio Tinto Limited",
"currency_code": "AUD",
"pe_ratio": 14.95,
"nta": 27.77,
"eps": 4.66,
"current_price": 69.66,
"current_price_updated_at": "2017-10-26T16:10:11.000+11:00",
"sector_classification_name": "Non-Energy Minerals",
"industry_classification_name": "Other Metals/Minerals",
"security_type": "Ordinary Shares",
"registry_name": "Computershare"
},
],
"links": {}
}
The array I need to pull out into its own JSON object is the instruments array.
Now typically I know I would access that data via (if the response variable was called data) data.instruments[0].name as a example which would give me Wesfarmers limited
but if I want that entire array to sit in a new variable, which can then be parsed, how can I get that to happen?
Cheers
arr=new Array(data.instruments)

Indexing array values in an object in an IndexedDB

For a Chrome app, wich stores data in IndexedDB, i have a object like this:
var simplifiedOrderObject = {
"ordernumber": "123-12345-234",
"name": "Mr. Sample",
"address": "Foostreet 12, 12345 Bar York",
"orderitems": [
{
"item": "brush",
"price": "2.00"
},
{
"item": "phone",
"price": "30.90"
}
],
"parcels": [
{
"service": "DHL",
"track": "12345"
},
{
"service": "UPS",
"track": "3254231514"
}
]
}
If i store the hole object in an objectStore, can i use an index for "track", which can be contained multiple times in each order object?
Or is it needed or possibly better/faster to split each object into multiple objectStores like know from relational DBs:
order
orderitem
parcel
The solution should also work in a fast way with 100.000 or more objects stored.
Answering my own question: I have made some tests now. It looks like it is not possible to do this with that object in only 1 objectStore.
An other example object which would work:
var myObject = {
"ordernumber": "123-12345-234",
"name": "Mr. Sample",
"shipping": {"method": "letter",
"company": "Deutsche Post AG" }
}
Creating an index will be done by:
objectStore.createIndex(objectIndexName, objectKeypath, optionalObjectParameters);
With setting objectKeypath it is possible to address a value in the main object like "name":
objectStore.createIndex("name", "name", {unique: false});
It would also be possible to address a value form a subobject of an object like "shipping.method":
objectStore.createIndex("shipping", "shipping.method", {unique: false});
BUT it is not possible to address values like the ones of "track", which are contained in objects, stored in an array. Even something like "parcels[0].track" to get the first value as index does not work.
Anyhow, it would be possible to index all simple elements of an array (but not objects).
So the following more simple structure would allow to create an index entry for each parcelnumber in the array "trackingNumbers":
var simplifiedOrderObject = {
"ordernumber": "123-12345-234",
"name": "Mr. Sample",
"address": "Foostreet 12, 12345 Bar York",
"orderitems": [
{
"item": "brush",
"price": "2.00"
},
{
"item": "phone",
"price": "30.90"
}
],
"trackingNumbers": ["12345", "3254231514"]
}
when creating the index with multiEntry set to true:
objectStore.createIndex("tracking", "trackingNumbers", {unique: false, multiEntry: true});
Anyhow, the missing of the possibility to index object values in arrays, makes using indexedDB really unneeded complicated. It's a failure in design. This forces the developer to do things like in relational DBs, while lacking all the possibilities of SQL. Really bad :(

Categories

Resources