Accessing a JavaScript object property names with a "-" in it [duplicate] - javascript

This question already has answers here:
How do I reference a JavaScript object property with a hyphen in it?
(11 answers)
Closed 9 years ago.
I have a requirement to read JSON data in my application. Problem is that the JSON data that I am getting from the service includes "-" and when I am trying to read it, I am getting "Uncaught ReferenceError: person is not defined ". e.g.
I have below JSON object-
var JSONObject ={
"name-person":"John Johnson",
"street":"Oslo West 16",
"age":33,
"phone":"555 1234567"};
when I am writing below console log statement I am getting "Uncaught ReferenceError: person is not defined " error
console.log(JSONObject.name-person);
Can someone please help me how to read such data which includes "-" in it? I do not have control on the service and the DB so to modify source data is not in my hand.

Try this way:
JSONObject["name-person"]
A JSON is an object, which is composed by key-value pairs, an object key can have any character or even reserved keywords (like for, function, if...), to access an object item by its key when it doesn't obbey the rules for a valid identifier (http://coderkeen.com/old/articles/identifiers-en.html), you have to use [ ].
Here's a funny example of what I'm talking about:
var strangeObject = {" ...this is a TOTALLY valid key!!! ": 123,
"function": "what a weird key..."};
console.log(strangeObject [" ...this is a TOTALLY valid key!!! "],
strangeObject ["function"]);

Use the [] syntax to access the property.
JSONObject['name-person']

Related

How can access nested JSON objects with this server response [duplicate]

This question already has answers here:
How can I access and process nested objects, arrays, or JSON?
(31 answers)
Closed 3 years ago.
I'm trying to parse the response retrieved from a proxied lambda function. I'm using an Ajax call. It fails when I attempt to get the nested Json.
This is the response from the server:
{
"vehicles": "{\"language\":\"fr-FR\",\"id\":\"10107\",\"make\":\"Panoz\",\"model\":\"Roadster\",\"generation\":\"AIV\",\"yearFrom\":\"1996\",\"yearTo\":\"1999\",\"serie\":\"Roadster\",\"trim\":\"4.6 MT (309 ch)\",\"vehicle\":{\"make\":\"Panoz\",\"model\":\"Roadster\",\"generation\":\"AIV\",\"yearFrom\":\"1996\",\"yearTo\":\"1999\",\"serie\":\"Roadster\",\"trim\":\"4.6 MT (309 ch)\",\"id\":\"10107\",\"bodyWork\":{\"rearTrack\":\"Roadster\",\"width\":\"2\",\"cargoCompartmentVolume\":\"4040\",\"curbWeight\":\"1950\",\"length\":\"1190\",\"numberOfSeater\":\"2655\",\"minTrunkCapacity\":\"1700\",\"maxTrunkCapacityLitre\":\"1620\",\"bodyType\":\"Non disponible\",\"height\":\"Non disponible\",\"fullWeight\":\"Non disponible\",\"cargoCompartment\":\"Non disponible\",\"loadingHeight\":\"1160\",\"frontRearAxleLoad\":\"130\",\"permittedRoadTrainWeight\":\"140\",\"payload\":\"140\",\"frontTrack\":\"Non disponible\",\"wheelbase\":\"Non disponible\",\"groundClearance\":\"Non disponible\"},\"engine\":{\"strokeCycle\":\"Essence\",\"cylinderBore\":\"4601\",\"presenceOfIntercooler\":\"309\",\"boostType\":\"de 5 800\",\"valvesPerCylinder\":\"407\",\"injectionType\":\"Distribué injection\",\"cylinderLayout\":\"V-forme\",\"maximumTorque\":\"8\",\"maxPowerAtRpm\":\"Non disponible\",\"turnoverOfMaximumTorque\":\"90\",\"enginePower\":\"90\",\"capacity\":\"4\",\"engineType\":\"à 4 800\",\"numberOfCylinders\":\"Non disponible\"},\"gearBoxAndHandling\":{\"gearboxType\":\"Manuel\",\"numberOfGear\":\"Arrière\",\"driveWheels\":\"Non disponible\",\"turningCircle\":\"5\"},\"operatingCharacteristics\":{\"cruisingRange\":\"95\",\"fuel\":\"250\",\"emissionStandards\":\"13\",\"fuelTankCapacityLitre\":\"Non disponible\",\"accelerationZeroToHundred\":\"4\",\"maxSpeed\":\"de 330 à 430\",\"cityDrivingFuelConsumptionPer100kmLitre\":\"Non disponible\",\"highwayDrivingFuelConsumptionPer100\":\"43\",\"mixedDrivingFuelConsumptionPer100\":\"10\"},\"suspensionAndBrakes\":{\"rearBrakes\":\"Disques ventilés\",\"frontBrakes\":\"Disques ventilés\",\"backSuspension\":\"Sur bras transversaux\",\"frontSuspension\":\"Barre stabilisatrice\"}},\"dateCreated\":1560071289997,\"dateUpdated\":1560071289997}",
"language": "fr-FR",
"id": "10107"
}
var vehicle = JSON.parse(data.vehicles);
console.log("vehicle: " + vehicle);
console.log("make: " + vehicle.make);
console.log("bodyWork: " + vehicle.bodyWork);
The instruction vehicle.make returns the correct value.
However when attempting to access the vehicle.bodyWork I receive an undefined answer.
When trying to stringify the data returned, I see the complete correct String. It's as if JSON.parse stopped parsing the first level attributes and couldn't parse the nested objects hence the undefined.
You're accessing it wrong, like #str said, the value you're looking for is found at vehicle.vehicle.bodyWork. The first vehicle stores the entire object, the second has the nested vehicle object and that has the bodyWork key.

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.

My object is not recognizing the key that is already been set

I have this snippet of code (unfortunately it won't work for you unless you have a qualtrics account and go into preview survey and run it in the console) that keeps throwing the error (Cannot set property 'questions0' of undefined). Yet I just added an object named ArrayOfBlocks2 to the main object. Can someone tell my why its saying ArrayOfBlocks2 is undefined?
Qualtrics.SurveyEngine.setEmbeddedData("ArrayOfBlocks",ArrayOfBlocks)
var ArrayOfBlocks1 = Qualtrics.SurveyEngine.getEmbeddedData("ArrayOfBlocks")
for(i=0;i<Qualtrics.SurveyEngine.getEmbeddedData("ArrayOfBlocks").length;i++){
for(k=0;k<Qualtrics.SurveyEngine.getEmbeddedData("ArrayOfBlocks")[i].BlockElements.length;k++){
var ArrayOfBlocks2 = ArrayOfBlocks1[i].ID
console.log(ArrayOfBlocks2)
ObjectIDWithQuestions[ArrayOfBlocks2]={}
Qualtrics.SurveyEngine.setEmbeddedData("OBID",ObjectIDWithQuestions);
ObjectIDWithQuestions.ArrayOfBlocks2["questions"+ k]=Qualtrics.SurveyEngine.getEmbeddedData("ArrayOfBlocks")[i].BlockElements[k].QuestionID
Qualtrics.SurveyEngine.setEmbeddedData("ObjectIDWithQuestions",ObjectIDWithQuestions)
}
}
I expect it to not throw an error, and to set "questions + k" as a object key.
Embedded data won't store an array by default, you will likely need to json encode the data before storing, and json parse the data on retrieval.

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.

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