Cannot access keys inside Object [duplicate] - javascript

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.

Related

How to set a Javascript Symbol as an Object Key?

I have a unique case where I need to use a Javacript symbol as an object's key. This is necessary because in order to conform to Sequelize's documentation, there are instances where we need to have something that looks like this:
const where = {
cost: {
[Op.gt]: 1000,
[Op.lt]: 2000
}
}
Both [Op.gt] and [Op.lt] are Javascript symbols that assist with querying. The block of code will query where a property called cost is greater than 1000 but less than 2000. But when I try to programmatically set the key/value pairs like:
where['cost'][[Op.gt]] = 1000;
I receive the following error:
Cannot convert a Symbol value to a string
This is a dynamic object, so I cannot hard code the symbols into the where query since the next user may not need to query by these parameters. How do I go about this? Thanks!
Remove 1 bracket around your symbol and you will be fine:
where['cost'][Op.gt] = 1000;
obj[Op.gt] means you're accessing an object property with the Op.gt name. obj[[Op.gt]] means you're accessing an object property with the name equal to an array [Op.gt] stringified. Which is similar to below:
const arr = [Op.gt];
const propertyName = arr.toString(); // => throw error "Cannot convert a Symbol value to a string"
where['cost'][propertyName];

Javascript string/object/array confusion with JSON

I'm having a Laravel backend return some errors via Validator. These errors are passed through a HTTP response made by angular, and returned in JSON format.
The object is structured as seen below:
That name object has a value, which is the actual message that I'm after.
Currently, using loops etc., I can only get the name of the array (name) as a string...
I sometimes get multiple arrays within this error object, and I won't always know their names, so how may I retrieve that 0-index value in each of them, in a loop?
Thanks for any help.
Edit #1
Looping through it like this:
for(var err in res.data.errors){
console.log(Object.err[0][0]);
}
Gives me a Cannot get [0] index of undefined
How about this:
let errors = Object.values(response.data.errors);
// errors is now an array of arrays containing the validation errors
errors.forEach( (errorArray) => {
console.log(errorArray[0]);
} );
Another approach would be using Object.keys() instead of values. This is similar to what you already tried, where you get the name of the error property as a string, and then use it to access each error array:
let keys = Object.keys(response.data.errors);
keys.forEach( (errorKey) => {
console.log('error type', errorKey);
let errorArray = response.data.errors[errorKey];
console.log(errorArray[0]);
} );

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];

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

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']

Categories

Resources