Javascript looping through an object - arrays

I have an object which is given back through my REST API and I need to iterate through it for synchronizing a DB. So the object contains another object called tables. The tables object has different arrays with table names and their key value pairs.
I could not loop through the tables object about two days whatever I did and it is really annoying getting null or undefined values back.
For example I tried iterating through the table array with the JavaScript function object.forEach((article)=>console.log(article.id,article.name));
const obj = response.content.tables.article;
function findArticles(obj) {
obj.forEach((article)=>console.log(article.id,article.name));
}
I can't get any value back. When I try to console.log(response.content); it shows me everything. As soon as I try to output response.content.tables it says undefined.
This is the structure of the object response.content:
{
"status": "1",
"message": "sync out request successfull",
"tables": {
"article": [
{
"id": 1,
"name": "baseball"
},
{
"id": 2,
"name": "truck"
},
],
"food": [],
"animals: []
}
}

Try converting the response to an object using JSON.parse(xyz) before attempting to get the properties.
var xyz = '{ "status": "1", "message": "sync out request successfull", "tables": { "article": [{"id": 1,"name": "baseball"},{"id": 2,"name": "truck"}],"food": [],"animals": []}}'
var obj = JSON.parse(xyz);
$(obj.tables).each(function (ix, el) {
console.log(el)
});

I solved it like this:
var obj = response.content;
var JSON = JSON.parse(obj);
var articleTable = JSON.tables.article;
articleTable.forEach((article)=>console.log(article.id,article.name));
After I parsed the response.content object to JSON it was available to access the nested objects as 'tables' and 'article'. After passing the article object with the articleTable variable to the forEach it has been possible to access each elements. Now I get results.
I really appreciate your help
T3.0 it wasn't able to solve the problem without you.

Related

How to write a test for nested JSON response from enterprise application

I'm trying to use Postman as a test tool to validate that our customers all have a mailing address in our master system. I'm having trouble drilling down into the JSON due to its structure. Each response is an array structure with a single "node" that has no "head attribute" to address.
Example JSON:
[
{
"ID": "cmd_org_628733899",
"organization": {
"name": "FULL POTENTIAL",
"accountStatusCode": "1",
"accountStatusDescription": "OPEN"
},
"location": [
{
"locality": "LITTLE ROCK",
"locationType": "MAILING"
},
{
"locality": "BIG ROCK",
"locationType": "LOCATION"
}
]
}
]
Test code as it exists:
pm.test("Check for a Mailing Address", function () {
// Parse response body
var jsonData = pm.response.json();
// Find the array index for the MAILING Address
var mailingLocationIndex = jsonData.location.map(
function(filter) {
return location.locationType;
}
).indexOf('MAILING');
// Get the mailing location object by using the index calculated above
var mailingLocation = jsonData.location[mailingFilterIndex];
// Check that the mailing location exists
pm.expect(mailingLocation).to.exist;
});
Error message: TypeError: Cannot read property 'map' of undefined
I understand that I have to iterate to node(0) in the outer array and then drill into the nested location array to find an entry with a locationType = Mailing.
I can't get past the outer array. I'm new to JavaScript and JSON parsing - I am a COBOL programmer.
Knowing nothing else, I would say you mean this
pm.test("Check for a Mailing Address", function () {
var mailingLocations = pm.response.json().location.filter(function (item) {
return item.locationType === 'MAILING';
});
pm.expect(mailingLocations).to.have.lengthOf(1);
});
You want to filter out all the locations that have a MAILING type and there should be exactly one, or at least one, depending.
Whether pm.response.json() actually returns the object you show in your question is impossible to say from where I'm standing.
In modern JS, the above is shorter:
pm.test("Check for a Mailing Address", function () {
var mailingLocations = pm.response.json().location.filter(item => item.locationType === 'MAILING');
pm.expect(mailingLocations).to.have.lengthOf(1);
});

How to assign multi level Json data array to single Angular object?

I have a json data like below
{
"data": {
"points": 390,
"medal": "gold",
"activeGoals": [{
"examType": full,
"dateApplied": null,
"status": "Active-GoodStanding",
"term": 2,
"amountPaid": 2500,
"pointEarned": null,
"examDetails": {
"totalAmountPaid": 4500,
"examDate": 1459449000000,
"endDate": 1554057000000,
"totalMarks": 100,
"nextExamDate": 1493577000000,
"interestRate": 0
}
}]
}
}
In this Json data there is 'activeGoal' array,and inside of that there is an another array 'examDetails'
In Controller,I tried assigning these data into the angular object like below
examCtrl.details ={};
examCtrl.details =data;
examCtrl.activeGoals=data.activeGoals;
examCtrl.examDetails=data.activeGoals.examDetails;
I am getting activeGoals, but for examDetails I am getting 'undefined' error.
What is the wrong i am doing here??
assign like this : examCtrl.examDetails=data.activeGoals[0].examDetails;
since activeGoals is itself an array and you need first index([0]) value of it i.e., examDetails.
Further: as per your JSON examDetails is object not array.
if you're confused what the exactly the data is you can always convert in JSON editor.then you can easily assign the object from JSON data.

iterate over json object of arrays from ionic 2 post request

I guess I'm stuck on stupid. I've been at this for the last few hours and can't seen to figure it out. Admittedly, I am new to ng/ionic2.
I am trying to loop through the response from my post request. I am getting a valid(validated online) big, fat JSON object from my own web api. It looks like this:
`"details": [{
"item_ID": "4",
"item_attribute_ID": "JiggyJamband_1_642",
"item_color_bool": "false",
"item_name": "Test Item 4",
"item_price": "18.95",
"item_desc": "4 This is a test of the ajax input",
"item_gender": "Girls"
},
{ ... },
"attributes": {
"JiggyJamband_1_642": [{
"color": "no-color",
"Xs": "80",
"Sm": "0",
"Med": "0",
"Lrg": "0",
"Xl": "0",
"Xxl": "10"
}],
"JiggyJamband_5_5664": [{
"color": "no-color",
"Xs": "0",
"Sm": "0",
"Med": "0",
"Lrg": "0",
"Xl": "0",
"Xxl": "50"
}],
{ ... }`
I am able to access individual "details" and "attributes" like this:
this.itemsDataService.getRemoteData(urlCode)
.subscribe(response => {
this.itemsJson = response;
this.dObj = this.boothItemsJson.details;
//this.aObj = this.boothItemsJson.attributes;
this.aObj = response["attributes"]["JiggyJamband_1_642"];
});
My provider looks like this:
getRemoteData(urlCode): any {
return this.http.post('http://localhost/process-fe-app/_itemJson.php', JSON.stringify(urlCode))
.map(res => res.json()); }
My question: items in details is dynamic and has an item-attribute_ID that is related to at least 1 entry in attributes. Entrys for attributes are dynamic as well - each item can have multiple attributes. The array keys of the individual attributes are the static (sizes and colors) and either have values or they don't. I need to be able to loop over the attributes object (aObj) of arrays and the arrays inside them. I do not need the ngFor or ngIf statements as this data won't be directly displayed per se. The json data is returned just fine but I just need to be able to access it call methods on the based on the data (like putting into storage with the attribute ID as the key "JiggyJamband: color: no-color, xs:50, s:100... etc"
What I've tried: this tutorial https://www.youtube.com/watch?v=0kHJgw6Li_4, and googling ever iteration of the wording for this problem I could think of.
Perhaps this sample iteration will help you get your head around it.
this.itemsDataService.getRemoteData(urlCode)
.subscribe(response => {
for(var k in response){
for(var k2 in response[k]){
console.log([k,k2,response[k][k2]]);
}
}
});

equalTo returning null from Firebase?

In my React Native App, I currently am trying to pull all items that have the selected property set to "true" from the database. However, when I log the results of this query, they are all being returned as null (even though expected response should be returning two objects). My relevant code as well as Firebase structure are included below, please let me know if you spot anything.
const rootRef = new Firebase(`${ config.FIREBASE_ROOT }`)
var queryRef = rootRef.orderByChild("items/selected");
var solution = queryRef.equalTo("true").once('value', function(snap) {
console.log(snap.val())
});
Firebase JSON:
"items":
[
{
"title":"ball",
"selected": "false"
},
{
"title":"dog",
"selected": "true"
},
{
"title":"phone",
"selected": "false"
},
{
"title":"cup",
"selected": "true"
}
],
When you run an Firebase query on a location, it takes each child node under that location and then evaluates the condition you specify. If you take each child under items, you'll see there is no path items/selected under there.
You query is instead:
var itemsRef = rootRef.child("items");
var queryRef = itemsRef.orderByChild("selected");
You should use
where("selected" = true)
instead of equalTo()

Trouble with updating object properties in AngularJs

I am building my first app in AngularJs.
Here is the plunkr with what I've done so far. The user should be able to add new websites and group them in groups. Groups are also made by the user. Any time the new group is created it is available for new websites. What app should also do is to update group objects with newly assigned websites... and this is where I fail.
Here is how json should look like:
{
"sites": [
{
"url": "http://sfdg",
"id": 0,
"groups": [
{
"name": "adsf",
"id": 0
}
]
}
],
"groups": [
{
"name": "adsf",
"id": 0,
"sites": [//sites assigned
]
}
]
}
In the plunkr code I used push but that just adds new group...
Could you please direct me to the right way of achieving this.
Thanks!
To prevent circular references (a website object refers to a group object that refers to the website object, etc...), I would store id's to the relevant objects instead.
First, when creating a new group, add an empty sites array to it:
function createGroup(newGroup) {
newGroup.sites = []; // <-- add empty array of sites
$scope.groups.push(newGroup);
newGroup.id = groupIdSeq;
groupMap[newGroup.id] = newGroup;
groupIdSeq++;
return newGroup;
}
Then, when you create a new site, update each group to which the site is added:
function createSite(newSite, groups) {
$scope.sites.push(newSite);
newSite.id = siteIdSeq;
sitesMap[newSite.id] = newSite;
// instead of storing the groups array, only store their id:
newSite.groups = groups.map(function(group) { return group.id });
// and add this new sites id to the groups' sites array.
groups.forEach(function(group) {
group.sites.push(newSite.id);
});
siteIdSeq++;
return newSite;
}
(updated plunker here)

Resources