Accessing JSON object Data - javascript

I have a page that sends a request to a RESTful web service (via php and curl). That page receives a JSON object as a response. I am trying to fill some form fields using the data that was returned. The object javascript that gets echoed onto my page looks like:
var obj = {
"NPI": [
{
"NPI": "123456789",
"EntityType": "Individual",
"IsSoleProprietor": "N",
"LastName": "Smith",
"FirstName": "John",
"MiddleName": "D",
"NameSuffix": "JR.",
"Credential": "MD",
"FirstLineMailingAddress": "PO BOX 123",
"MailingAddressCityName": "SCOTTSDALE",
"MailingAddressStateName": "AZ",
"MailingAddressPostalCode": "85255-0162",
"MailingAddressCountryCode": "US",
"MailingAddressTelephoneNumber": "888-123-4567",
"MailingAddressFaxNumber": "888-123-4567",
"FirstLinePracticeLocationAddress": "123 DR",
"SecondLinePracticeLocationAddress": "#278",
"PracticeLocationAddressCityName": "SCOTTSDALE",
"PracticeLocationAddressStateName": "AZ",
"PracticeLocationAddressPostalCode": "85266-2273",
"PracticeLocationAddressCountryCode": "US",
"PracticeLocationAddressTelephoneNumber": "888-123-4567",
"PracticeLocationAddressFaxNumber": "888-123-4567",
"EnumerationDate": "09/20/2006",
"LastUpdateDate": "02/07/2011",
"GenderCode": "M",
"Gender": "Male",
}
]
};
alert(obj.NPI.NPI);
What is the syntax to access these object properties. The alert statement below doesn't work (it alerts "Undefined").
Thanks for the help

try obj.NPI[0].NPI this should work
the propblem is that the first NPI is an array not an object so because of the presence of the [] so you should select which element in the array

Your obj.NPI is an array of objects.

Try this
console.log(obj.NPI[0].NPI);
console.log(obj.NPI[0].EntityType);
//etc
Your structure is like this
{// Start of object
"NPI": //First element, access it as obj.NPI
[ // NPI is an array
{ // First element of the array is an object
"NPI": "123456789", // Then access each element of this object using dot notation
"EntityType": "Individual",
................................

Related

How can get only want object value from firestore by react native

I try to get only object value that I want but whenever I query with array-contains in where() ,come out all data value from that collection.
getid Array [
Object {
"timestamp": Object {
"nanoseconds": 738000000,
"seconds": 1639994269,
},
"userMatch": Array [
"6Lf5bHwzCSbI2bmoMv7KuduMGwe2",
"E8R52y6dD8XI3shXhnhS9pVzUpe2",
],
"users": Object {
"6Lf5bHwzCSbI2bmoMv7KuduMGwe2": Object {
"about": "gshjs",
"age": "25",
"displayName": "ry",
"gender": "female",
"id": "6Lf5bHwzCSbI2bmoMv7KuduMGwe2",
"interestIn": "male",
"job": "fh",
"photo": "https://firebasestorage.googleapis.com/v0/b/match-me-now.appspot.com/o/images%2F6Lf5bHwzCSbI2bmoMv7KuduMGwe2%2FprofilePicture.jpeg?alt=media&token=e1b8d794-4074-4e10-93f1-e2f5c9835fa2",
"timestamp": Object {
"nanoseconds": 44000000,
"seconds": 1639994173,
},
},
"E8R52y6dD8XI3shXhnhS9pVzUpe2": Object {
"about": "fdhnsn",
"age": "25",
"displayName": "gsj",
"gender": "male",
"id": "E8R52y6dD8XI3shXhnhS9pVzUpe2",
"interestIn": "female",
"job": "hsh",
"photo": "https://firebasestorage.googleapis.com/v0/b/match-me-now.appspot.com/o/images%2FE8R52y6dD8XI3shXhnhS9pVzUpe2%2FprofilePicture.jpeg?alt=media&token=b93935cf-8285-4059-8495-2243fdb89fff",
"timestamp": Object {
"nanoseconds": 201000000,
"seconds": 1639994235,
},
},
},
},
]
I only want is userMatch (E8R52y6dD8XI3shXhnhS9pVzUpe2) id value
"userMatch": Array [
"6Lf5bHwzCSbI2bmoMv7KuduMGwe2",
"E8R52y6dD8XI3shXhnhS9pVzUpe2",
],
I fetch as follow
useEffect(async()=>{
const matchid = query(collection(db,'matches'),where('userMatch','array-contains',user.uid))
const getid = await getDocs(matchid).then((snapshot)=>snapshot.docs.map((doc)=>doc.data()))
console.log('getid',getid)
},[db])
why not get only user.uid in userMatch object.
although where() method filter 'userMatch' object field, why get all object field in matches collection.how can get only userMatch object value.
plz help
Firestore client-side SDKs always returns entire documents. They have no way to retrieve only some fields of a document.
A query (as you use here with array-contains can be used to limit which documents are returns from the database, but not what field are returned.
If you commonly find that you only need some fields from a larger document, consider storing those fields in a separate document. While you'll be duplicating data, you'll have less data to read when needed.
In your use-case you could also consider storing the userMatches in a subcollection for each user document, and then using a collection group query to find the relevant documents.
Also see:
How to get a list of document IDs in a collection Cloud Firestore?
How to access a specific field from Cloud FireStore Firebase in Swift

Does reading file in node.js guarantee the order of items

In my node.js application I have test data file that I read to populate some inputs. The test file contains an array of objects.
I use for reading:
data = fs.readFileSync(fileName, "utf8");
My test file:
[
{
"firstname": "John",
"lastname": "Doe",
"birthdate": "01/01/1970"
},
{
"firstname": "El",
"lastname": "Maestro",
"birthdate": "01/01/1989",
"isDeleted": true
}
]
So the question is - when I read this file is it guaranteed that I will always get object with name "John" at index 0, and "El" at index 1?
Arrays always ensures order in JS
BUT
Keys inside objects doesnot ensure order in JS, they are 'unordered key value pair'
To answer your question:
when I read this file is it guaranteed that I will always get object with name "John" at index 0, and "El" at index 1
yes
BUT
The keys in the resulting object can be unordered, eg: it can be
{
"firstname": "John",
"lastname": "Doe",
"birthdate": "01/01/1970"
}
or
{
"lastname": "Doe",
"birthdate": "01/01/1970",
"firstname": "John"
}
etc...

How to iterate through following compex JSON data and access its all values including nested?

I have following JSON data but I don't know how to iterate through it and read its all values:
var students = {
"student1": {
"first_name": "John",
"last_name": "Smith",
"age": 24,
"subject": [{
"name": "IT",
"marks": 85
},
{
"name": "Maths",
"marks": 75
},
{
"name": "English",
"marks": 60
}
]
},
"student2": {
"first_name": "David",
"last_name": "Silva",
"age": 22,
"subject": [{
"name": "IT",
"marks": 85
},
{
"name": "Maths",
"marks": 75
},
{
"name": "English",
"marks": 60
}
]
}
};
I would like to use following methods to do the needful:
Using for in loop
Using simple for loop
Using $.each in jQuery
I will prefer to display above values in <ul> <li> nicely formatted.
Also, please suggest me what will be look of above JSON data if I put it in an external .json file?
You can use for in loop to iterate over the object, as it iterates over the properties of an object in an arbitrary order, and needs to use .hasOwnProperty, unless inherited properties want to be shown.
Now about accessing the object, let's say I have a JSON like
var myJson={name:"john",age:22,email:"email#domain.com"};
and I need to access the value of name i would simply use . operator using the myJson variable i.e console.log(myJson.name) will output john. because it will be treated as an object, now if I make a little change and make the object like below
var myJson=[{name:"john",age:22,email:"email#domain.com"}];
now if you try to access the value of the property name with the same statement above you will get undefined because the [] will now treat it as an object(JSON) with an array of 1 person or a JSON Array, now if you access it like console.log(myJson[0].name) it will print john in console what if there was more than one person in the array? then it will look like following
var myJson=[
{name:"john",age:22,email:"john#domain.com"},
{name:"nash",age:25,email:"nash#domain.com"}
];
console.log(myJson[0].name) will print john and console.log(myJson[1].name) will print nash so as I mentioned in the start that you should use for in loop for iterating over an object and if we want to print all the names of the person in the JSON Array it will be like.
for(var person in myJson){
console.log(myJson[person].name, myJson[person].age, myJson[person].email);
}
it will output in the console like below
john, 22, john#domain.com
nash, 25, nash#domain.com
I have tried to keep it simple so that you understand you can look into for in and hasOwnProperty, in your case you have a nested object in which property/key subject is an array so if I want to access the first_name of student1 i will write students.student1.first_name and if I want to print the name of the first subject of student1 I will write students.student1.subject[0].name
Below is a sample script to print all the students along with their subjects and marks and personal information since you JSON is nested I am using a nested for in, although Nested iterations are not necessarily a bad thing, even many well-known algorithms rely on them. But you have to be extremely cautious what you execute in the in the nested loops.
For the sake of understanding and keeping the given example of json object, i am using the same to make a snippet. Hope it helps you out
var students = {
"student1": {
"first_name": "John",
"last_name": "Smith",
"age": 24,
"subject": [{
"name": "IT",
"marks": 85
},
{
"name": "Maths",
"marks": 75
},
{
"name": "English",
"marks": 60
}
]
},
"student2": {
"first_name": "David",
"last_name": "Silva",
"age": 22,
"subject": [{
"name": "IT",
"marks": 85
},
{
"name": "Maths",
"marks": 75
},
{
"name": "English",
"marks": 60
}
]
}
};
$("#print").on('click', function() {
for (var student in students) {
console.log(students[student].first_name + '-' + students[student].last_name);
for (var subject in students[student].subject) {
console.log(students[student].subject[subject].name, students[student].subject[subject].marks);
}
}
setTimeout('console.clear()', 5000);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="button" id="print" value="print-now">

Delete an object in Scope

This question might not even be related to angularjs and the solution could be plain old js or jquery. But that is what i what to find out.
I want to implement a delete functionality for a particular user and i am wondering if there is a easier way to do this in angularjs or should it be plain old JS?
i have a fairly complex object for eg (going up to 4 levels):
{
"Department": [
{
"Name": "Accounting",
"users": [
{
"id": "1",
"firstName": "John",
"lastName": "Doe",
"age": 23
},
{
"id": "2",
"firstName": "Mary",
"lastName": "Smith",
"age": 32
}
]
},
{
"Name": "Sales",
"users": [
{
"id": "3",
"firstName": "Sally",
"lastName": "Green",
"age": 27
},
{
"id": "4",
"firstName": "Jim",
"lastName": "Galley",
"age": 41
}
]
}
]
}
this is displayed in a ng-repeat where we should Department and username. If I want to delete a particular user i make an api call and on success of it, I want to delete that object. so i have a js method like this
function DeleteUser(user) {
$.each(ctrl.UserData, function(index, value) {
var filteredPeople = value.filter((item) => item.id !== user.id);
});
The question I have is, if i want to delete this object is there any easier way to delete from model since i have the object here or i have to do the classic jquery way of using like $.grep or filter to iterate through each object and match by id and then delete it?
Presumably, you're iterating over the departments (accounting, sales) in your template, and then over the users in that department.
So you could have, in your template:
<button ng-click="deleteUser(user, department)">...</button>
And the method could thus be as simple as
$scope.deleteUser = function(user, department) {
// delete user from backend, then
department.users.splice(departments.users.indexOf(user), 1);
}
If you really don't want to pass the department, then loop over the departments, and use the above if departments.users.indexOf(user) returns a value that is >= 0.

How to access the data from return JSON from webservice in javascript or jquery

Hi i have a return json data which returns the webservice
The structure of webservice is like that:
jsonp1332655154667({"products": [{"uid": "37",
"samsid": "hjk",
"name": "Science%20Essentials%2010%20AC%20edn",
"shortname": "scienceessentials10",
"description": "Science%20Essentials%2010%20ACE%20is%20the%20fourth%20in%20a%20series%20of%20four%20books%20designed%20for%20the%20National%20Curriculum.%20",
"generated": "3/25/2012%205:59:19%20AM",
"Description": "Science%20Essentials%2010%20ACE%20is%20the%20fourth%20in%20a%20series%20of%20four%20books%20designed%20for%20the%20National%20Curriculum.%20",
"PublishingCompany": "Macmillan%20Australia",
"Service": "OneStopScience",
"Service": "OneStopDigital",
"Icon": "http://curriculumplatform.s3.amazonaws.com/prod/icons/brain48.png",
"Country": "Australia",
"Shortname": "scienceessentials10",
"MarketingSite": "http%3a%2f%2fwww.macmillan.com.au%2fsecondary%2fonix%2fall%2f6F597241EFC0E43DCA257791001CAFC0%3fopen%26div%3dSecondary%26cat%3dScience%253EAustralian%252BCurriculum%26template%3ddomSecondary%26ed%3dsite%2fseced31.nsf",
"Skin": "OneStopScience%20Green"},
"tag":"s_science"'
"tag":"s_maths"'
"tag":"s_arts",
{"uid": "5",}]})
I have three "tag" elements. but when we access the products.tag it gives always last element like:s_arts.
Is there any way to find out all the elements eg:s_science,s_maths,s_arts.
please help.
It is invalid json, your tag should be:
...,
"tag": ["s_science", "s_maths", "s_arts" ],
...
Then product.tag would be an array that you could access successfully
Regards
If you have multiple keys in the same object, you're going to get undefined behaviour. Only one will be preserved, and since pairs are not ordered, you can't guarantee which you'll get.
In short: the webservice is returning you faulty data. If multiple tags are expected, the service should return an array of values in the tag attribute:
...
"tag":["s_science", "s_maths", "s_arts"],
...
You need to send the tags as an array:
jsonp1332655154667({"products": [{"uid": "37",
"samsid": "hjk",
"name": "Science%20Essentials%2010%20AC%20edn",
"shortname": "scienceessentials10",
"description": "Science%20Essentials%2010%20ACE%20is%20the%20fourth%20in%20a%20series%20of%20four%20books%20designed%20for%20the%20National%20Curriculum.%20",
"generated": "3/25/2012%205:59:19%20AM",
"Description": "Science%20Essentials%2010%20ACE%20is%20the%20fourth%20in%20a%20series%20of%20four%20books%20designed%20for%20the%20National%20Curriculum.%20",
"PublishingCompany": "Macmillan%20Australia",
"Service": "OneStopScience",
"Service": "OneStopDigital",
"Icon": "http://curriculumplatform.s3.amazonaws.com/prod/icons/brain48.png",
"Country": "Australia",
"Shortname": "scienceessentials10",
"MarketingSite": "http%3a%2f%2fwww.macmillan.com.au%2fsecondary%2fonix%2fall%2f6F597241EFC0E43DCA257791001CAFC0%3fopen%26div%3dSecondary%26cat%3dScience%253EAustralian%252BCurriculum%26template%3ddomSecondary%26ed%3dsite%2fseced31.nsf",
"Skin": "OneStopScience%20Green"},
"tags": [
"s_science"'
"s_maths"'
"s_arts"
],
{"uid": "5",}]})
Then you reference them as data.tags[0], data.tags[1], data.tags[2].
if your response is in this format
YourResponse = {
"products" : [
{"uid" :"5", ......., "whtever":"someval"},
{"uid" :"6", ......., "whtever":"someval1"}
]
};
you can use this
$(YourResponse).each(
function(objName, objValue) {
console.log(objName); // wil get object name like uid, whtever
console.log(objValue); // wil get object's value
});
so to get Tags you will have to take Tuan's suggestion; send them in array

Categories