Referencing object with dollar sign - javascript

Given the following object, how is the email property referenced? I've been trying variations of getresponse.partner[0].email to no avail.
{"getresponse":{"$":{"unpagedCount":"10"},"partner":[{"$":{"id":"p1e","type":"content","name":"myname","status":"active","email":"me#here.com","peopleIds":"9","personIds":"9"},"ketchup":[""]}]}}
thanks in advance!
-b

$ is a valid property/variable name in Javascript. Just use it like any other property name:
let $$$ = {
"getresponse": {
"$": {
"unpagedCount": "10"
},
"partner": [{
"$": {
"id": "p1e",
"type": "content",
"name": "myname",
"status": "active",
"email": "me#here.com",
"peopleIds": "9",
"personIds": "9"
},
"ketchup": [""]
}]
}
}
console.log($$$.getresponse.partner[0].$.email);

Just access it as a normal key in any JS object via getresponse.partner[0].$.email. Note that $ is a legal variable identifier name, as you can check in this other post.
var obj = {"getresponse":{"$":{"unpagedCount":"10"},"partner":[{"$":{"id":"p1e","type":"content","name":"myname","status":"active","email":"me#here.com","peopleIds":"9","personIds":"9"},"ketchup":[""]}]}}
var email = obj.getresponse.partner[0].$.email
console.log(email)

Related

How to get specific array from JSON object with Javascript?

I am working with facebook JS SDK which returns user's information in JSON format. I know how to get the response like response.email which returns email address. But how to get an element from a nested array object? Example: user's education history may contain multiple arrays and each array will have an element such as "name" of "school". I want to get the element from the last array of an object.
This is a sample JSON I got:-
"education": [
{
"school": {
"id": "162285817180560",
"name": "Jhenaidah** School"
},
"type": "H**hool",
"year": {
"id": "14404**5610606",
"name": "2011"
},
"id": "855**14449421"
},
{
"concentration": [
{
"id": "15158**968",
"name": "Sof**ering"
},
{
"id": "20179020**7859",
"name": "Dig**ty"
}
],
"school": {
"id": "10827**27428",
"name": "Univer**g"
},
"type": "College",
"id": "9885**826013"
},
{
"concentration": [
{
"id": "108196**810",
"name": "Science"
}
],
"school": {
"id": "2772**996993",
"name": "some COLLEGE NAME I WANT TO GET"
},
"type": "College",
"year": {
"id": "1388*****",
"name": "2013"
},
"id": "8811215**16"
}]
Let's say I want to get "name": "some COLLEGE NAME I WANT TO GET" from the last array. How to do that with Javascript? I hope I could explain my problem. Thank you
Here is a JsFiddle Example
var json = '{}' // your data;
// convert to javascript object:
var obj = JSON.parse(json);
// get last item in array:
var last = obj.education[obj.education.length - 1].school.name;
// result: some COLLEGE NAME I WANT TO GET
If your json above was saved to an object called json, you could access the school name "some COLLEGE NAME I WANT TO GET" with the following:
json.education[2].school.name
If you know where that element is, then you can just select it as already mentioned by calling
var obj = FACEBOOK_ACTION;
obj.education[2].school.name
If you want to select specifically the last element, then use something like this:
obj.education[ obj.education.length - 1 ].scool.name
Try this,
if (myData.hasOwnProperty('merchant_id')) {
// do something here
}
where JSON myData is:
{
amount: "10.00",
email: "someone#example.com",
merchant_id: "123",
mobile_no: "9874563210",
order_id: "123456",
passkey: "1234"
}
This is a simple example for your understanding. In your scenario of nested objects, loop over your JSON data and use hasOwnProperty to check if key name exists.

How to use jquery to handle multiple json objects

I am developing a website with front-end and back-end separated. I used jquery to send request and get the result as a json object:
{
"item": [
],
"shop": [
],
"user": [
{
"user_id": "9",
"full_name": "Minh Duc",
"email": "nguyenminhduc1803#gmail.com",
"fb_link": "https:\/\/www.facebook.com\/SieuNhan183",
"user_name": "Duc",
"password": "37cd769165eef9ba6ac6b4a0fdb7ef36",
"level": "0",
"admin": "0",
"dob": "1996-03-18",
"location": "Ho Chi Minh",
"user_image_url": null
}
]
}
Now i am finding a way to get the data from the object user. How can i do it with javascript?
Complementing #arcs answer, remember that in Javascript you can access members of an object using dot notation (data.user[0].user_id) or square brackets notation. This way:
data['user'][0]['user_id']
this is useful because you can have a 'class' array and then do things like:
['item', 'shop', 'user'].forEach((array) => processArray(data[array][0]));
then you can filter only some classes or do more advanced stuff
When you have the data (in example it's in data) use the dot notation to get the node with the user.
The user is an array, so use [] to access a single element, e.g. [0]
var data = {
"item": [
],
"shop": [
],
"user": [
{
"user_id": "9",
"full_name": "Minh Duc",
"email": "nguyenminhduc1803#gmail.com",
"fb_link": "https:\/\/www.facebook.com\/SieuNhan183",
"user_name": "Duc",
"password": "37cd769165eef9ba6ac6b4a0fdb7ef36",
"level": "0",
"admin": "0",
"dob": "1996-03-18",
"location": "Ho Chi Minh",
"user_image_url": null
}
]
}
console.log( data.user[0].user_id )
I prefer use square brackets like this :
$jsonObject["user"][0]["user_id"]
but you can use the dot like this :
data.user[0].user_id
is the same thing.
If you want check if property exist you can do it :
if(typeof $jsonObject["user"] !== 'undefined'){
//do domethings as typeof $jsonObject["user"][0]["user_id"]
}
If you want get property dinamically you can do it :
const strId = "id";
const strName = "name";
//get user_id
let user_id = $jsonObject[user][0]["user_" + strId ];
//get user_name
let user_name = $jsonObject[user][0]["user_" + strName];
but there isn't very pretty.

How to use a variable as an index to get a specific value out of a JSON array in Javascript?

I simply want to pinpoint a specific value out of a JSON array.
Sample of JSON array:
{
"00002": {
"Job Number": "00002",
"Company": "Corporate",
"Supervisor": "Great Person",
"Date Input": "2016-01-07"
},
"00003": {
"Job Number": "00003",
"Company": "SmallGuy",
"Supervisor": "Awful Person",
"Date Input": "2012-03-05"
}
}
This works in Javascript:
alert(javascript_array["00002"].Company);
But I want use a dynamic variable to call a record, like this:
var my_variable = 00002;
//OR I've tried:
var my_variable = "'"+00002+"'";
alert(javascript_array[my_variable].Company); //DOES NOT WORK. UNDEFINED??
No matter what I do, I can't use a variable mid-array call.
Help please!
Use the string as key.
var my_variable = '00002';
var object = { "00002": { "Job Number": "00002", "Company": "Corporate", "Supervisor": "Great Person", "Date Input": "2016-01-07" }, "00003": { "Job Number": "00003", "Company": "SmallGuy", "Supervisor": "Awful Person", "Date Input": "2012-03-05" } }
my_variable = '00002';
document.write(object[my_variable].Company);
For getting all keys from the object, you can use Object.keys():
var object = { "00002": { "Job Number": "00002", "Company": "Corporate", "Supervisor": "Great Person", "Date Input": "2016-01-07" }, "00003": { "Job Number": "00003", "Company": "SmallGuy", "Supervisor": "Awful Person", "Date Input": "2012-03-05" } },
keys = Object.keys(object);
keys.forEach(function (k) {
document.write(object[k].Company + '<br>');
});
Your key is a string, but your variable isn't, so there's no match. Just use this:
var my_variable = "00002";
To access key items for a JSON object you need to use strings, but if not it will attempt to convert the value into a string using .toString(). For your first case you are attempting to define a number:
var my_variable = 00002;
Although 00002 isn't a valid value for a number, as such it will contain the value 2, and converted to a string it's "2". In your JSON there is no such javascript_array["2"]. The second case has a similar problem:
"'"+00002+"'" => "'"+2+"'" => "'2'"
Also there is not such javascript_array["'2'"], along with this you are adding unneeded quotes '...'. In this case (as others pointed out) just define my_variable as a string with the value "00002".
var my_variable = "00002";

How to check the value is in object with Chai?

Is it possible to test the value is contained within certain array with Chai assertion library?
Example:
var myObject = {
a : 1,
b : 2,
c : 3
};
var myValue = 2;
I need to do something like this (however it is not working):
expect(myObject).values.to.contain(myValue);
//Error: Cannot read property 'to' of undefined
expect(myObject).to.contain(myValue);
//Error: Object #<Object> has no method 'indexOf'
How can I test this?
Alternatively if you want to check the value along with the property you can do
expect(myObject).to.have.property('b', myValue);
You won't need the plugin for this check.
The chai fuzzy plugin has the functionality you needed.
var myObject = {
a : 1,
b : 2,
c : 3
};
var myValue = 2;
myObject.should.containOneLike(myValue);
if the object is bit nested, like
{
"errors": {
"text": {
"message": "Path `text` is required.",
"name": "ValidatorError",
"properties": {
"message": "Path `{PATH}` is required.",
"type": "required",
"path": "text",
"value": ""
},
"kind": "required",
"path": "text",
"value": "",
"$isValidatorError": true
}
},
"_message": "todos validation failed",
"message": "todos validation failed: text: Path `text` is required.",
"name": "ValidationError"
}
then do an assertion on errors.text.message, we can do like
expect(res.body).to.have
.property('errors')
.property('text')
.property('message', 'Path text is required.');

Reading JSON data for a particular ID

I have some JSON data which is in the following format:
[
{
"id": 145,
"Name": "John",
"company_name": "A",
"email": "john#gmail.com",
"country": "USA"
},
{
"id": 500,
"Name": "Mike",
"company_name": "B",
"email": "mike#gmail.com",
"country": "London"
},
{
"id": 100,
"Name": "Sally",
"company_name": "C",
"email": "sally#gmail.com",
"country": "USA"
}
]
Now, suppose I ask the user to enter an id, say 100. Then I need to display all the details for this id.
I am supposed to do this as a part of a web application,where I have to invoke an display the fields of a particular id. This would have been easy if I had a hash like implementation and could display all parameters based on the key-id.
Can anybody tell me how this can be done using such kind of data?
Thanks!
You could use something like this:
(Assuming the you have a variable data with your Json Object).
function getid(id) {
var nobj;
data.forEach(function(obj) {
if(obj.id == id)
nobj = obj;
});
return nobj
}
var neededobj = getid(100);
console.log(neededobj.Name + "\n" + neededobj.email + "\netc...");
But to get the Object you have to loop through your complete array,
until it finds the right Object
see this Fiddle
I think you are looking for Associative Array,
the simplex one would be,
var associativeArray = [];
associativeArray["one"] = "First";
associativeArray["two"] = "Second";
associativeArray["three"] = "Third";
alert(associativeArray.one);
And obviusly you can add json object in value place

Categories