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

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

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 append value in an existing object without change the first object with javascript? [duplicate]

This question already has answers here:
Clone Object without reference javascript [duplicate]
(4 answers)
Closed 5 years ago.
My javascript code like this :
var data= {product_id: 4, name: 'nike'}
console.log(data)
var dataNew = data
dataNew.id = 1
console.log(dataNew)
Demo is like this : https://jsfiddle.net/oscar11/69dw8dv1/
I append value in the object like that
The result of console.log(data) and console.log(dataNew) is there exist id
I want var data is no id
So there is only var dataNew that has id
How can I do it?
In JavaScript, object references are assigned, instead of the object values, unless the object is of primitive data types.
That's why dataNew and data refers to the same object when you do this:
var dataNew = data;
To prevent this, you need to create a copy of data like this:
var dataNew = Object.assign({}, data);
Now, the changes in dataNew won't affect data.

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

Prevent referencing the same object when adding it multiple times to an array [duplicate]

This question already has answers here:
How do I correctly clone a JavaScript object?
(81 answers)
Closed 7 years ago.
I have an object similar to the sample object below.
var obj = {
id : "",
entries: [
{
url : "some url",
response : {a response object}
},
{
url : "another url",
response : {a response object}
}
]
};
In the above object I have an entries element which is an array of object. Each object inside entries element will have a 'url' property and a 'response' property which is an object.
In the object there can be missing response property in entries. In such instance, I have a default response object in a variable 'tempObj' and I assign this tempObj to the 'entries' element.
var tempObj = {
status : 200
statusText : "Success"
};
obj.entries[1]["response"] = tempObj;
The problem is when there are multiple response elements missing in obj it adds a response element correctly for the first missing entries, but for the second entries it adds a reference to the first element added.
I need to add the exact value in the second element as well. How can I do this?
This is in nodejs application (not client side javascript).
Just loop through the entries array, and update where necessary. For example:
var tempObj = {
status : 200,
statusText : "Success"
};
obj.entries.forEach(function(item){
item.response = item.response || tempObj;
});
If you need the default response to be unique for each item, then just use your favourite cloning method, and apply it on the assignment line. eg, see here: What is the most efficient way to deep clone an object in JavaScript?
Update: When I need to do cloning, or anything for that matter that is common but extends regular js, I usually turn to lodash. You an clone easily with this library, and it works on both node.js and frontend clients. To clone you would do something like:
item.response = item.response || _.assign({}, tempObj);

JSON using parse or stringify correctly [duplicate]

This question already has answers here:
How can I access and process nested objects, arrays, or JSON?
(31 answers)
Closed 8 years ago.
This is what I'm getting from server
['model':{"category":[{"id":1}],"food":[{"id":1}].... // long json here
How can I use jquery/javascript to parse to get category id and food id? I tried to use
JSON.parse(data)
or
JSON.stringify(data)
And after that, doing
$.each(data, function (i, x) {
it will give me each letter of all array. How can I parse it correctly, getting the ids that I want?
JSON.parse(data) will turn the data you showing into a JavaScript object, and there are a TON of ways to use the data from there. Example:
var parsedData = JSON.parse(data),
obj = {};
for(var key in parsedData['model']){
obj[key] = parsedData['model'][key]['id'];
}
Which would give you a resulting object of this:
{category:1, food:1}
This is based on the limited example of JSON you provided, the way you access it is entirely dependent on its structure. Hopefully this helps get you started, though.
You want to use JSON.parse(), but it returns the parsed object, so use it thusly:
var parsed = JSON.parse(data);
then work with parsed.

Categories

Resources