How to destructure json data in JavaScript - javascript

Giving this json data , how can I Modify it to use object de-structuring to get just the dob property of the parameter object, having troubles understanding please
{
"results":[
{
"gender":"female",
"name":{
"title":"ms",
"first":"emily",
"last":"simmons"
},
"location":{
"street":"1514 preston rd",
"city":"mackay",
"state":"victoria",
"postcode":3943,
"coordinates":{
"latitude":"-82.6428",
"longitude":"99.3586"
},
"timezone":{
"offset":"-5:00",
"description":"Eastern Time (US & Canada), Bogota, Lima"
}
},
"email":"emily.simmons#example.com",
"login":{
"uuid":"4db43a8c-f811-4f66-9063-8de9af1b7ff4",
"username":"brownlion857",
"password":"girls",
"salt":"Fff9zzxa",
"md5":"4eb010fc1f3e9f72b6298b75cec001a1",
"sha1":"086f0a1c0db596967033a77df62e21e6d407f647",
"sha256":"d7f99aae053957d788fe17a80922877d04a491bd7ea00d7b6b41c94329468e12"
},
"dob":{
"date":"1992-10-20T03:47:03Z",
"age":26
},
"registered":{
"date":"2012-02-25T19:05:12Z",
"age":7
},
"phone":"09-1749-9293",
"cell":"0490-139-057",
"id":{
"name":"TFN",
"value":"338334455"
},
"picture":{
"large":"https://randomuser.me/api/portraits/women/64.jpg",
"medium":"https://randomuser.me/api/portraits/med/women/64.jpg",
"thumbnail":"https://randomuser.me/api/portraits/thumb/women/64.jpg"
},
"nat":"AU"
}
],
"info":{
}
}
I did something like this:
const displayBirthdate = ( {results: [{dob: {date, age } }]}) =>
{
}
Is there a way I can make it simpler to just get the dob parameter for the function?

You can declare your variables using Destructuring assignment:
const json = {"results": [{"gender": "female","name": {"title": "ms","first": "emily","last": "simmons"},"location": {"street": "1514 preston rd","city": "mackay","state": "victoria","postcode": 3943,"coordinates": { "latitude": "-82.6428", "longitude": "99.3586"},"timezone": { "offset": "-5:00", "description": "Eastern Time (US & Canada), Bogota, Lima"}},"email": "emily.simmons#example.com","login": {"uuid": "4db43a8c-f811-4f66-9063-8de9af1b7ff4","username": "brownlion857","password": "girls","salt": "Fff9zzxa","md5": "4eb010fc1f3e9f72b6298b75cec001a1","sha1": "086f0a1c0db596967033a77df62e21e6d407f647","sha256": "d7f99aae053957d788fe17a80922877d04a491bd7ea00d7b6b41c94329468e12"},"dob": {"date": "1992-10-20T03:47:03Z","age": 26},"registered": {"date": "2012-02-25T19:05:12Z","age": 7},"phone": "09-1749-9293","cell": "0490-139-057","id": {"name": "TFN","value": "338334455"},"picture": {"large": "https://randomuser.me/api/portraits/women/64.jpg","medium": "https://randomuser.me/api/portraits/med/women/64.jpg","thumbnail": "https://randomuser.me/api/portraits/thumb/women/64.jpg"},"nat": "AU"}],"info": {}};
const {results: [{dob: {date, age}}]} = json;
console.log('date:', date);
console.log('age:', age);
According to the comment:
how would i make it a function parameter, like dob for instance?
const json = {"results": [{"gender": "female","name": {"title": "ms","first": "emily","last": "simmons"},"location": {"street": "1514 preston rd","city": "mackay","state": "victoria","postcode": 3943,"coordinates": { "latitude": "-82.6428", "longitude": "99.3586"},"timezone": { "offset": "-5:00", "description": "Eastern Time (US & Canada), Bogota, Lima"}},"email": "emily.simmons#example.com","login": {"uuid": "4db43a8c-f811-4f66-9063-8de9af1b7ff4","username": "brownlion857","password": "girls","salt": "Fff9zzxa","md5": "4eb010fc1f3e9f72b6298b75cec001a1","sha1": "086f0a1c0db596967033a77df62e21e6d407f647","sha256": "d7f99aae053957d788fe17a80922877d04a491bd7ea00d7b6b41c94329468e12"},"dob": {"date": "1992-10-20T03:47:03Z","age": 26},"registered": {"date": "2012-02-25T19:05:12Z","age": 7},"phone": "09-1749-9293","cell": "0490-139-057","id": {"name": "TFN","value": "338334455"},"picture": {"large": "https://randomuser.me/api/portraits/women/64.jpg","medium": "https://randomuser.me/api/portraits/med/women/64.jpg","thumbnail": "https://randomuser.me/api/portraits/thumb/women/64.jpg"},"nat": "AU"}],"info": {}};
const getDate = dob => ({date, age} = dob);
console.log('displayBirthdate:', getDate(json.results[0].dob));

You could combine de-structuring with mapping for more readable code:
const data = {
"results": [{
"gender": "female",
"name": {
"title": "ms",
"first": "emily",
"last": "simmons"
},
"location": {
"street": "1514 preston rd",
"city": "mackay",
"state": "victoria",
"postcode": 3943,
"coordinates": {
"latitude": "-82.6428",
"longitude": "99.3586"
},
"timezone": {
"offset": "-5:00",
"description": "Eastern Time (US & Canada), Bogota, Lima"
}
},
"email": "emily.simmons#example.com",
"login": {
"uuid": "4db43a8c-f811-4f66-9063-8de9af1b7ff4",
"username": "brownlion857",
"password": "girls",
"salt": "Fff9zzxa",
"md5": "4eb010fc1f3e9f72b6298b75cec001a1",
"sha1": "086f0a1c0db596967033a77df62e21e6d407f647",
"sha256": "d7f99aae053957d788fe17a80922877d04a491bd7ea00d7b6b41c94329468e12"
},
"dob": {
"date": "1992-10-20T03:47:03Z",
"age": 26
},
"registered": {
"date": "2012-02-25T19:05:12Z",
"age": 7
},
"phone": "09-1749-9293",
"cell": "0490-139-057",
"id": {
"name": "TFN",
"value": "338334455"
},
"picture": {
"large": "https://randomuser.me/api/portraits/women/64.jpg",
"medium": "https://randomuser.me/api/portraits/med/women/64.jpg",
"thumbnail": "https://randomuser.me/api/portraits/thumb/women/64.jpg"
},
"nat": "AU"
}],
"info": {}
}
const [ dob ] = data.results.map(item => item.dob)
console.log(dob)
// {date: "1992-10-20T03:47:03Z", age: 26}

Related

Verify String is displaying within Nested JSON using Postman

I am working on Postman to verify some API calls, upon which I have gone through one of the end point, whose response is give below, and I need to make sure that within that JSON response:
[
{
"contact": {
"id": "k72yk2iwrf",
"firstName": "Francis",
"lastName": "Abell",
"title": "Translational Science Project Manager",
"company": "Sensei",
"email": "aa#aa.cpom",
"fax": {},
"businessAddress": {
"line1": "road",
"line2": "Street",
"line3": "Suite 710",
"city": "Boston",
"country": "US",
"postalCode": "02210",
"state": "MA"
},
"businessPhone": {
"number": "123-123-1234",
"ext": ""
},
"homeAddress": {},
"homePhone": {},
"mobilePhone": {}
},
"registration": {
"id": "104656",
"badgeId": "9208113975",
"eventId": "TESTLIBRA-10"
}
},
{
"contact": {
"id": "w4c4f2i7l4",
"firstName": "Francis",
"lastName": "Abell",
"title": "Translational Science Project Manager",
"company": "Sensei",
"email": "aa#aa.cpom",
"fax": {},
"businessAddress": {
"line1": "road",
"line2": "Street",
"line3": "Suite 710",
"city": "Boston",
"country": "US",
"postalCode": "02210",
"state": "MA"
},
"businessPhone": {
"number": "123-123-1234",
"ext": ""
},
"homeAddress": {},
"homePhone": {},
"mobilePhone": {}
},
"registration": {
"id": "104656",
"badgeId": "6803424516",
"eventId": "TESTLIBRA-10"
}
}
]
I can make sure that "eventId" is displaying and it is displaying "TESTLIBRA-10" value.
No matter, how long JSON response is, It can verify that this property , along with that value of that property are displaying.
I got my answer by myself, what I did was:
var jsonArrayData = pm.response.json();
pm.test('EventID property is displaying throughout JSON', function(){
jsonArrayData.each(function(eventID){
pm.expect(eventID.registration).to.have.property("eventId")
})
})
pm.test('Entered Libra EventID is entered', function(){
jsonArrayData.each(function(eventID){
pm.expect(eventID.registration.eventId).to.eql("TESTLIBRA-10")
})
})

filter nest array of object using java script

This the data i need this value only email": "gm#gmail.com"
{
"params": {
"user": {
"address1": "790 7th Ave",
"address2": "hhhdkhdskhsdkh",
"city": "Chennai",
"name": "gm4",
"phone": "",
"state": "TN",
"zipcode": "600008"
},
"query": {
"FILTERS": [
[
{
"EQ": {
"email": "gm#gmail.com"
}
}
]
],
"PAGENUM": 1,
"PAGESIZE": 100,
"SELECTCOLUMNS": [],
"SORT": []
},
"trigger": "User::UserUpdated"
},
"context": {}
}
actually, I tried const out = req.params.query.FILTERS[0].EQ.email
but i field unable to get expect result plz help.
It is a nested array.
req.params.query.FILTERS[0][0].EQ.email

Fetch value based in that same JSON key value

I have the JSON like
var resultJSON = `{
"data": {
"total": 1,
"list_name": "title",
"title": {
"id": 53,
"name": "Sonu",
"mobileNo": "6543213456",
"address": "Greeny Pathway",
"city": "NewYork",
"mode": "Weekly",
"duration": "15",
"qty": null
},
"download": [{
"time": "16789042",
"date": "26 - 01 - 2020"
}]
}
}`;
I expect the output:
{
"total": "1",
"list_name": "title",
"name": "sonu",
"mobileno": "6543213456"
}
Here "list_name": "title" is dynamic, sometimes it will come "list_name": "book", based on that above mentioned response I want to get.
Something like this? I had to fix your invalid JSON
You can make it more clever if you study https://javascript.info/destructuring-assignment in depth
const resultJSON = `{
"data": {
"total": 1,
"list_name": "title",
"title": {
"id": 53,
"name": "Sonu",
"mobileNo": "6543213456",
"address": "Greeny Pathway",
"city": "NewYork",
"mode": "Weekly",
"duration": "15",
"qty": null
},
"download": [{
"time": "16789042",
"date": "26-01-2020"
}]
}
}`
const data = JSON.parse(resultJSON).data
const content = data[data.list_name];
let newObj = {}
newObj["total"] = data["total"];
newObj["list_name"] = data["list_name"];
newObj["name"] = content["name"];
newObj["mobileNo"] = content["mobileNo"];
console.log(newObj)

filter thought the contacts that have secondary numbers

Im trying to filter and take only the contacts that the number is in numbers my problem is that one numbers could be the secondary number of the contact and filter(indexOf(foreach())) doesn't seem to work here any advice?
const filteredContacts = contacts.filter(contact => numbers.indexOf(contact.phoneNumbers.forEach(phone => phone.number)) > -1);
//sample of contacts
Object {
"company": "Financial Services Inc.",
"contactType": "person",
"firstName": "Hank",
"id": "2E73EE73-C03F-4D5F-B1E8-44E85A70F170",
"imageAvailable": false,
"jobTitle": "Portfolio Manager",
"lastName": "Zakroff",
"middleName": "M.",
"name": "Hank M. Zakroff",
"phoneNumbers": Array [
Object {
"countryCode": "us",
"digits": "5557664823",
"id": "337A78CC-C90A-46AF-8D4B-6CC43251AD1A",
"label": "work",
"number": "(555) 766-4823",
},
Object {
"countryCode": "us",
"digits": "7075551854",
"id": "E998F7A3-CC3C-4CF1-BC21-A53682BC7C7A",
"label": "other",
"number": "(707) 555-1854",
},
],
},
Object {
"contactType": "person",
"firstName": "David",
"id": "E94CD15C-7964-4A9B-8AC4-10D7CFB791FD",
"imageAvailable": false,
"lastName": "Taylor",
"name": "David Taylor",
"phoneNumbers": Array [
Object {
"countryCode": "us",
"digits": "5556106679",
"id": "FE064E55-C246-45F0-9C48-822BF65B943F",
"label": "home",
"number": "555-610-6679",
},
],
},
]
//Sample of numbers
numbers = [
(707) 555-1854,
555-610-6679
]
//Expected
filteredContacts = //Both contacts
This should work for you:
const contacts= [
{
company: "Financial Services Inc.",
// ....
phoneNumbers:[
{
//...
number: "(555) 766-4823",
},
{
//...
number: "555-610-6679",
}
]
}
//...
];
//Sample of numbers
const numbers = [
'(707) 555-1854',
'555-610-6679'
]
const filteredContacts = contacts.filter(contact => {
let number_exists=false;
contact.phoneNumbers.map(phone => phone.number).forEach( phoneNr =>{
if(numbers.indexOf(phoneNr)>-1) number_exists=true;
}
);
return number_exists;
}
);
//Expected
console.log(filteredContacts)

Parse JSON with multiple levels

I am trying to parse this JSON that I have assigned to a javascript variable but I am having a hard time looping through it due to it having multiple levels
<script type="text/javascript">
var varJson = {
"d": {
"results": [
{
"__metadata": {
"id": "http://www.bradinsight.com/ALFAPI/AlfWebApi/Offices(100013449)",
"uri": "http://www.bradinsight.com/ALFAPI/AlfWebApi/Offices(100013449)",
"type": "AlfWebApiInfrastructure.Poco.Office"
},
"Agency": {
"__deferred": {
"uri": "http://www.bradinsight.com/ALFAPI/AlfWebApi/Offices(100013449)/Agency"
}
},
"Advertiser": {
"__deferred": {
"uri": "http://www.bradinsight.com/ALFAPI/AlfWebApi/Offices(100013449)/Advertiser"
}
},
"Contacts": {
"results": [
{
"__metadata": {
"id": "http://www.bradinsight.com/ALFAPI/AlfWebApi/Contacts(id=59980,jobId=1000105450)",
"uri": "http://www.bradinsight.com/ALFAPI/AlfWebApi/Contacts(id=59980,jobId=1000105450)",
"type": "AlfWebApiInfrastructure.Poco.Contact"
},
"id": 59980,
"jobId": 1000105450,
"mask": 67108863,
"name": "Name",
"jobtitle": "Job Title",
"email": "email",
"companyType": "companyType",
"companyId": 1787,
"officeId": 100013449,
"address1": "address1",
"address2": "",
"address3": "",
"address4": "",
"addressTown": "addressTown",
"addressPostCode": "addressPostCode",
"tel": "tel",
"fax": "fax",
"responsibilities": "responsibilities"
},
{
"__metadata": {
"id": "http://www.bradinsight.com/ALFAPI/AlfWebApi/Contacts(id=64085,jobId=1000105448)",
"uri": "http://www.bradinsight.com/ALFAPI/AlfWebApi/Contacts(id=64085,jobId=1000105448)",
"type": "AlfWebApiInfrastructure.Poco.Contact"
},
"id": 64085,
"jobId": 1000105448,
"mask": 67108863,
"name": "name",
"jobtitle": "jobtitle",
"email": "email",
"companyType": "companyType",
"companyId": 1787,
"officeId": 100013449,
"address1": "address1",
"address2": "",
"address3": "",
"address4": "",
"addressTown": "addressTown",
"addressPostCode": "addressPostCode",
"tel": "tel",
"fax": "fax",
"responsibilities": "responsibilities"
}
]
},
"id": 100013449,
"companyId": 1787,
"addressLine1": "addressLine1",
"addressLine2": "",
"addressLine3": "",
"addressLine4": "",
"addressLine5": "addressLine5",
"postCode": "postCode",
"regionId": "regionId",
"countyId": "countyId",
"tvAreaId": "L",
"telephone": "telephone",
"fax": "fax8",
"countryId": "countryId",
"email": "email",
"isdn": null,
"mask": 66060287
}
]
}
};
$(document).ready(function () {
//var parsed = JSON.parse(varJson);
alert(varJson);
});
</script>
I tried using this:
$.each(varJson, function (index, item) {
alert(item);
});
But it just says object in my alert.
try this,
function traverse(jsonObj) {
if( typeof jsonObj == "object" ) {
$.each(jsonObj, function(k,v) {
traverse(v);
});
}
else {
alert(jsonObj);
}
}
$(document).ready(function () {
traverse(varJson);
});
http://jsfiddle.net/satpalsingh/hXEr8/
with reference of Traverse all the Nodes of a JSON Object Tree with JavaScript
You don't need to parse it in your example.
Use console.log instead of alert and you will the the object in your web inspector.
If you do want to alert do something like this
alert(varJson.d.results[0].__metadata.id)

Categories

Resources