access objects from json - javascript

I have an ajax call that receives a json encoded object on return.
success: function (response) {
jsonArrayResponse = jQuery.parseJSON(response["data"]);
autoSearchValue = jsonArrayResponse['autoresult'];
I want to be able to access the different parts of the decode. This is some sample return
{"success":true,"message":null,"messages":null,"data":"{\"errorText\":\"\",\"autoresult\":[{\"firstname\":\"Annon\",\"lastname\":\"Brooks\",\"date_of_birth\":\"1975-12-23 00:00:00\",\"id\":\"1\"},{\"firstname\":\"Josh\",\"lastname\":\"Ferns\",\"date_of_birth\":\"2000-09-02 00:00:00\",\"id\":\"2\"},
{\"firstname\":\"Alan\",\"lastname\":\"Templeton\",\"date_of_birth\":\"1975-08-02 00:00:00\",\"id\":\"3\"}}]}
I've found that I can access the firstname by
autoSearchValue[0]['firstname'];
but I can't figure out how to loop through the other firstname values. I'm guessing it's straightforward once you know how.
Any help would be great thanks

autoSearchValue is an array. Just use an index in a loop:
for (let index = 0; index < autoSearchValue.length; index++) {
autoSearchValue[index]['firstname'];
}

Maybe try to loop throught the length of the json object? Each loop will increment the counter since you get the first name with autoSearchValue[0]['firstname'] then find the next one with autoSearchValue[1]['firstname'] until the length is reached.

You can access by iteratig over the object. As an option you can use map function to iterate over the array, the callback function will receive current value on the argument
which you can either modify or process
autoSearchValue.map((value) => {
console.log(value.firstname)
})

Related

Uncaught TypeError: data.forEach is not a function at XMLHttpRequest.request.onload

I tried to make connection with the api restcountries.eu.
My javascript code:
var request = new XMLHttpRequest()
var arr = []
request.open('GET', 'https://restcountries.eu/rest/v2/alpha/col', true)
request.onload = function () {
// Begin accessing JSON data here
var data = JSON.parse(this.response)
data.forEach((countries) => {
arr.push(countries.name)
})
var selectBox = document.getElementById('test')
for(var i = 0; i < arr.length; i++){
selectBox.options.add(new Option(arr[i], arr[i]));
}
}
request.send()
I recieve the following error: Uncaught TypeError: data.forEach is not a function
at XMLHttpRequest.request.onload on the line where I use the foreach function.
I parsed the data before so I don't get it where it went wrong.
Is there a solution for this problem?
If you want to use the values of the items from the data variable, then you should first convert the values into an array. To get an array of the values of the object, you can do something like this:
Object.values(data).forEach(item=>{
arr.push(item.name);
});
Remember, .forEach() only works for arrays. So whenever you have an array of values, you can use Object.values(yourObjectHere) to get an array of its values. I think bluejayke mentioned that Object.keys(yourObjectHere) returns an array of its keys (properties).
The data at the URL https://restcountries.eu/rest/v2/alpha/col is not an array, it is a JavaScript object. If you want to traverse it's properties with forEach you have to call something like Object.keys or Array.from on the parsed data, like
Object.keys(data).forEach((k) => {
arr.push(data[k].name)
})
You are querying a specific country, specifically columbia. I think what your goal is, to create a list of options based on a list of countries. In that case, you will need to change your request url to https://restcountries.eu/rest/v2 to receive an entire list of countries that you can iterate over.

Possible to .push() to a dynamically named key?

I have an object that I would like to push an indeterminate amount of other objects to, using a loop. To keep it organized, I'd like to dynamically name the keys based on them amount of times the loop runs. I have the following:
let formsJson = {};
let counter = 1;
//savedForms are where the objects that I want to push reside
savedForms.forEach( form => {
formsJson['form'+counter] = JSON.parse(form.firstDataBit_json);
//This is where I'm having trouble
counter = counter + 1;
});
I can push the first bit of data fine, and name the key dynamically as well. But I need to push 2 more objects to this same dynamic key, and that's where I'm having trouble. If I try the obvious and do:
formsJson['form'+counter].push(JSON.parse(form.secondDataBit_JSON));
I don't get any output. Is there a way to accomplish this?
forEach() gives you access to the index already. No need to create the counter variable. Example usage. I would definitely recommend using a simple index, and not using the 'form'+counter key.
In your example, it's not clear to me that the value being assigned in the forEach loop is an array. So it's unclear if you can push to any given element in that. But generally that syntax should
Personally, I would prefer to have a function that outputs the entire value of the element. That would provide better encapsulation, testability, and help enforce default values. Something like:
function createItem(param1) {
let item = [];
item.push(param1.someElement);
if (foo) {
item.push(...);
} else {
item.push(...);
}
return item;
}
formsJson['form'+counter] = createItem( JSON.parse(form) )
So you're making formsJson['form'+counter] a by assigning the JSON parse, not an array as you want. Try this:
formsJson['form'+counter] = [];
formsJson['form'+counter].push(JSON.parse(form.firstDataBit_json));
formsJson['form'+counter].push(JSON.parse(form.secondDataBit_JSON));
Maybe you want to figure out something like this
savedforms.forEach((form, index) =>
formsJson[`form${index + 1}`] = [ JSON.parse(form.secondDataBit_JSON)])
Now you can push on the item
formsJson[`form${index + 1}`].push(JSON.parse(form.secondDataBit_JSON));`
Also here you'll save operation on incrementing it will be automaticly

How do I access this javascript object?

{"profit_center" :
{"branches":
[
{"branch": {"work_order":"1","cutover":"1","site_survey":"1","branch_number":"3310","quote":"1","configuration":"1","purchase_order":"1","hardware_swap":"1"}},
{"branch":{"work_order":"1","cutover":"1","site_survey":"1","branch_number":"3311","quote":"1","configuration":"1","purchase_order":"1","hardware_swap":"1"}},
{"branch":{"work_order":"1","cutover":"0","site_survey":"1","branch_number":"3312","quote":"1","configuration":"1","purchase_order":"1","hardware_swap":"1"}},
{"branch":{"work_order":"1","cutover":"1","site_survey":"1","branch_number":"3313","quote":"1","configuration":"1","purchase_order":"1","hardware_swap":"1"}},
{"branch":{"work_order":"1","cutover":"0","site_survey":"1","branch_number":"3314","quote":"1","configuration":"1","purchase_order":"1","hardware_swap":"1"}},
{"branch":{"work_order":"1","cutover":"1","site_survey":"1","branch_number":"3315","quote":"1","configuration":"1","purchase_order":"1","hardware_swap":"1"}}
],
"profit_center_name":"Alabama"}}
I tried accessing it in ajax through this,
data.profit_center //data here is the ajax variable e.g. function(data)
or through this data["profit_center"]
but no luck
How do I access this javascript object properly. ?
By the way that code above is from console.log(data)
EDIT:
Result from console.log(data.profit_center) and console.log(data["profit_center"]) is undefined
You can put your datain a variable like
var json = data
and you can access profit_center like
alert(json.profit_center);
alert(json.profit_center.profit_center_name); //Alabama
for(var i =0 ;i<json.profit_center.branches.length;i++){
alert(json.profit_center.branches[i]);
}
Okay I have found out why it is undefined, It is a json object so I need to parse it before i can access it like a javascript object.
var json = JSON.parse(data);
Then that's it.
First parse your data if you've not already done so.
You can access, for example, each branch_number like so:
var branches = data.profit_center.branches;
for (var i = 0, l = branches.length; i < l; i++) {
console.log(branches[i].branch.branch_number);
}
In summary, profit_center is an object and branches is an array of objects. Each element in the array contains a branch object that contains a number of keys. Loop over the branches array and for each element access the branch object inside using the key names to get the values.
The profit center name can be found by accessing the profit_center_name key on the profit_center object:
console.log(data.profit_center.profit_center_name); // Alabama
You could even use the new functional array methods to interrogate the data and pull out only those branches you need. Here I use filter to pull those objects where the purchase_order is equal to 2. Note that the numeric values in your JSON are strings, not integers.
var purchaseOrder2 = branches.filter(function (el) {
return el.branch.purchase_order === '2';
});
DEMO for the three examples

Store function result to variable

How can I store the result of a function to a variable?
In navigating an object that contains an array, I am looking for one value, value1, once that is found I want to get the value of one of its properties, property1.
The code I am using below is an example and is incorrect.
function loadSets(id){
clworks.containers.find(function(i){
return i.get('property1')===id;
});
}
My intent is to navigate the object below:
clworks.containers
containers[0].property0.id
containers[1].property1.id
I am trying to determine how to find which item in the array has a property value equal to the id used in the function and then store it as a variable.
Simply:
var myVar = loadSets(id);
EDIT
Ok, as much as I understand your question now, your situation is the following:
You have an array containing objects called containers;
You want to iterate through this array, looking for the property id of the property property1 which equals the one specified in the function called loadSets(id);
Once found, store the object with the requested id in a variable.
Am I right?
If so, this should solve your problem:
// This function iterates through your array and returns the object
// with the property id of property1 matching the argument id
function loadSets( id ) {
for(i=0; i < containers.length; i++) {
if( containers[i].property1.id === id )
return containers[i];
}
return false;
}
After this you just need to do what I said in the first answer to your question, triggering it however you want. I put up a quick JSBin for you. Try to put 10, or 20, in the input field and then hitting the find button; it will return the object you are looking for. Try putting any other number, it will return a Not found.
Currently your function, loadSets, isn't actually returning anything and so you cannot store a result from it.
Try:
function loadSets(id){
return Base.containers.find(function(i){
return i.get('entityid')===id;
});
}
And to get a result into a variable:
var result = loadSets(id);

jQuery .getJSON return into array variable & json array manipulation

is there any way I can get the return of $.getJSON into a variable array?
I know its async and out of scope, but I will use it inside ajax callback, I just need to get all the values first and check them against another array.
Something like:
$.getJSON('itemManager.php?a=getItems', function(data){
// itemArray = new Array(data);
// idsArray = new Array(data.id);
for (var i in someOtherArray){
if($.inArray(i, idsArray) == -1){
// do something...
// get jason variable by id?
// itemArray[i].someVariable
}
}
}
EDIT: JSON structure
[{"id":"786","user_id":"1","seller_id":"2","address_id":"1","time":1299852115,"publicComment":null,"personalComment":null},
{"id":"787","user_id":"1","seller_id":"2","address_id":"1","time":1299852115,"publicComment":null,"personalComment":null},
{"id":"785","user_id":"1","seller_id":"2","address_id":"1","time":1299852114,"publicComment":null,"personalComment":null},
{"id":"784","user_id":"1","seller_id":"2","address_id":"1","time":1299852113,"publicComment":null,"personalComment":null},
{"id":"783","user_id":"1","seller_id":"2","address_id":"1","time":1299852111,"publicComment":null,"personalComment":null}]
This is basically the idea.
Get all the values
Isolate the id values of JSON objects
Loop another array
Check if json id is inside the other array
Access other json variables by id value
There are various solutions here I guess, but I'm looking for something with minimal code.
With the given information, there is not shortcut to test the existence of IDs. You really have to loop over everything. However you can improve a bit by creating an id => object mapping:
$.getJSON('itemManager.php?a=getItems', function(data){
var items = {};
for(var i = data.length; i--; ) {
items[data[i].id] = data[i];
}
for (var j = someOtherArray.length; j--; ){
var item = items[someOtherArray[j]];
if(item){
// do something with `item`
}
}
}
It woud be even better if you create this structure on the server already, then it would be:
$.getJSON('itemManager.php?a=getItems', function(data){
for (var j = someOtherArray.length; j--; ){
var item = data[someOtherArray[j]];
if(item){
// do something with `item`
}
}
}
You should also consider which arrays will contain more elements, data or someOtherArray and adjust your data structures such that you loop over the smaller array only.
Update:
To create the appropriate structure on the server with PHP, you have to create an associate array.
So at the point where you add an object to the array, you should not do
$items[] = $obj;
but
$items[$obj->id] = $obj; // or $obj['id'] if you have an array
If you get an array as your JSON response then your data variable in your callback is an array, no need to do anything with it.
If you get an object as your JSON response as the data.id in you example might suggest, and some of it's values is an array, then just use data.id as an array, or use var array = data.id; if that is more convenient for you.
Remember that data in your callback is just whatever you got as JSON. It can be an object (which is an associative array), an array, a string, a number, or a true, false or null value. If it is an object you access it using data.key, if it is an array you access it using data[index]. I say it because I suspect that you might be confusing arrays with objects here.

Categories

Resources