Traversing a non-standard object property in JavaScript [duplicate] - javascript

This question already has answers here:
JavaScript object: access variable property by name as string [duplicate]
(3 answers)
Valid javascript object property names
(3 answers)
Closed 8 years ago.
I am working with an API returning a response to me via AJAX, it returns the response in responseJSON so I access the part of the object I need with dot notation just like with any other AJAX call
var test = jqxhr.responseJSON.test;
A literal representation of the object would be:
test = {1_status: "invalid", 4_type: "domain.com", 1_type: "alpha.domain.com", 4_email: "admin#domain.com", 3_email: "admin#charlie.domain.com"…}
Which appears as so in the console after a console.log(test)
1_email: "admin#alpha.domain.com"
1_status: "invalid"
1_type: "alpha.domain.com"
2_email: "admin#bravo.domain.com"
2_status: "invalid"
2_type: "bravo.domain.com"
3_email: "admin#charlie.domain.com"
3_status: "invalid"
3_type: "charlie.domain.com"
4_email: "admin#domain.com"
4_status: "invalid"
4_type: "domain.com"
errorCode: "0"
How would I access the values by key like 1_email in a for loop interation like below.
for (var i = 1; i <= 4; i++){
// access key values here like so:
//console.log(test.i_email);
// where the console should return admin#alpha.domain.com on the first interation
}
If I simply do something like the below outside the loop where I manually call a certain key:
console.log(test.1_email);
I get the following:
Uncaught SyntaxError: Unexpected token ILLEGAL
I need to access each piece with [i]_status as I do not know the exact return values and the order changes, and unfortunately I do not have access to the API directly.
Any help is appreciated.

You could do this with an indexer.
test[i + '_email']

Related

Cannot access keys inside Object [duplicate]

This question already has answers here:
How to get objects value if its name contains dots?
(4 answers)
Closed 3 years ago.
I'm trying to access the value of a key inside a Javascript object. My object currently looks like:
const options = {
"account.country": getCountry,
"account.phone": getPhone,
}
When I console.log(options), it shows the whole object. But, when I try
console.log(options.account) // undefined,
console.log(options.account.country) // error.
I don't understand why. I also tried:
const parsedObj = JSON.parse(options);
console.log(parsedObj);
But it just returns
'Unexpected token o in JSON at position 1'
You should use Bracket Notation when you want to access the property from a string.
const options = {
"account.country": 'getCountry',
"account.phone": 'getPhone',
}
console.log(options['account.country'])
The . in object key name is causing this issue. When you do:
options.account it returns undefined
^ that is because there is no key with name account
when I console log 'options.account.country' it errors
^ that is because it tries to look for key country on undefined (options.account)
You can solve this by using array indexing syntax as follow:
options['account.country']
options['account.phone']
let options = {
"account.country": "getCountry",
"account.phone": "getPhone"
}
console.log(options["account.country"])
const options = {
"account.country": 'getCountry',
"account.phone": 'getPhone',
}
You can access the desired value using options['account.country']
When I console.log 'options', it shows the whole object
Because it is an object
when I console.log options.account it returns undefined
Because there is no account property.
Only account.country and account.phone. So you have to access properties with those explicit names, like this:
console.log(options['account.country']);
But it just returns 'Unexpected token o in JSON at position 1'
It's an object, not a string of JSON.

How to get every value in Json by key in Javascript [duplicate]

This question already has answers here:
JavaScript object: access variable property by name as string [duplicate]
(3 answers)
Closed 5 years ago.
I am making a rest call to a webservice. In its body it contains a Json file with 18 pairs key, value.
I which to make separate operations on each element so i would like to:
get the different key elements. so i would have an array of the key elements.
With each of those elements, get the corresponding value by dot walking.
Here is what I have:
var obj = JSON.parse(request.body.dataString);
var myKeys = Object.keys(obj)
for (var i = 0; i < myKeys.length; i++){
var iter = myKeys[i];
gs.log(obj.iter);
}
But the gs.log returns undefined.
I have tried to make this:
gs.log(obj.myId);
and it returns the value i want, since myId is one of the elements in keys.
How can i use the elements of my keys array to get the corresponding values?
I have confirmed that hte var myKeys has all the elements of keys and the var obj contains all the json file.
You need to use the [] syntax.
var iter = myKeys[i];
gs.log(obj[iter]);
Plain obj.iter tries to get a property called literally iter. If you want to get a property based on the string value of the variable iter, you need to access the object using obj[iter].

Accessing an object from a JSON array of objects yields "Undefined" [duplicate]

This question already has answers here:
How can I access and process nested objects, arrays, or JSON?
(31 answers)
Closed 6 years ago.
I'm using a Blockspring API that returns a JSON array of objects (read in from a Google Sheet). However, whenever I try to access an object from the array, an "undefined" value is returned. I have attached the code and the console log below. Does anyone have any ideas why?
blockspring.runParsed("query-public-google-spreadsheet", { "query": "SELECT A, B, C", "url":
"https://docs.google.com/spreadsheets/d/1ZYvcYf_41aghdXRSpg25TKW4Qj9p1Lpz92b1xG-9R1Q/edit?usp=sharing"},
{ "api_key": "br_50064_1fe91fe1478ef990dc8b5e9b4041c2c476670306" }, function(res){
var obj=res.params;
console.log(obj);
var temp=obj[0];
console.log(temp);
}
You need to use obj.data[0] to access the first element of an array.
Looking at your output in the console, it seems you are missing the data property of obj.
Object obj doesn't have a property with name 0 so it returns undefined.
I would need to play around with it myself but I can tell that the problem is just how you are accessing the info.
When you try to grab the data with var temp=obj[0] you are treating object like an array when is it not. I would recommend trying to grab the data using this:
//get the actual array
JSONArray theArray = obj.getJSONArray("data"); //I believe it is stored in an array called data... could be that the obj is just fine
// now get the first element:
JSONObject firstItem = theArray.getJSONObject(0);
// and so on
String name = firstItem.getString("Name"); // A
You most likely can grab it using var temp = obj.data[0];

Javascript JSON Array [duplicate]

This question already has answers here:
How can I access and process nested objects, arrays, or JSON?
(31 answers)
Closed 8 years ago.
I am using a get request from a server API and I am making a request and then doing this:
var resp = JSON.parse(response);
I call to the server providing 0001 & 0002 as arguments and
after the JSON.parse it returns an array such as:
{"0001":{"id":1},"0002":{"id":2}}
I know that traditionally if i were given static responses such as
{"placeID":{"id":1},"placeID":{"id":2}}
I could do this:
resp.placeId.id
but given that the return names aren't always the same how can I access that first value resp.0001.id given that 0001 may not always be the value returned?
Use a for...in loop.
for(var property in resp) {
console.log(property + ": " + resp[property]);
}
You can access the "0001" element of the response like this:
resp["0001"].id
Since you say that you're providing the id in the query, you presumably have it stored in a variable somewhere.
If you really want to access the first element in the response, you can't use JSON.parse, because you'll lose the ordering information once you suck that data into an object. And if you have to care about the order of the elements, then that JSON is badly-formed, and should be using an array instead of a top-level object.

Javascript array [duplicate]

This question already has answers here:
How and why does 'a'['toUpperCase']() in JavaScript work?
(12 answers)
Closed 9 years ago.
Im am working with some code from another developer and came across something I have not seen before. The basic functionality of the code is to look for a piece of data in an object within an object. The object format is theObj {key:Object, key:Object,...}, the data being searched for is stored in 2 variables inkey,lookfor.
$.each(theObj, function(m,n){
if(typeof(n['data'][inkey]) != "undefined" && n['data'][inkey] !== null) {
if(n['data'][inkey][lookfor] == 1){..}
}
});
What does the ['data'] do?
It is looking for a property data in the object n - n['data'] is the same as n.data
n['data'] is the same as n.data but sometime it's useful to use brackets like when you need to use a variable like n['data'][inkey].
Btw you or him should use n.data.hasOwnProperty(inkey) instead of typeof(n['data'][inkey]) != "undefined"
You could write it like that :
$.each(theObj, function(m,n){
if(n.data.hasOwnProperty(inkey) && n.data[inkey] !== null) {
if(n.data[inkey][lookfor] == 1){..}
}
});
data is the property name or key in the object. So n['data'] would return the property value for the property name data in object n.
And what you have is an Object not an Array.
Array contains list of elements with integer based index, where else Object contains list of elements with key based index.

Categories

Resources