Reputation: 976
I am stuck on a issue where i need to access a nested JSON with dynamic variables. This is my JSON:
{
"Account2": [{
"accountId": "17467****",
"containerId": "7454***",
"path": "accounts\/17467*****\/containers\/7454***",
}, {
"accountId": "17467****",
"containerId": "7519***",
"path": "accounts\/17467****\/containers\/7519***",
}],
"Account 1": [{
"accountId": "17661****",
"containerId": "7483***",
"path": "accounts\/17661****\/containers\/7483***",
}]
}
Using AngluarJS on front-end i use this to print a table, here i can use the "path" variable to use a href and then make second API call based on url parameters like this:
<td><a href="/gui/tags/{{v1.path}}">View Container</a></td>
v1.path = accounts/17467*****/containers/7454***
Now to my problem, i want to send this call before clicking on table to show some data. The problem is that when accessing the JSON that has dynamic variable as you can see: "Account2", "Account1". I cannot use: `$scope.GTMcontainersAccount = response.data.ACCOUNT1;
because "account1" is dynamic and changes from user to user.
Someone has an idea? regEx?
UPDATED:
when i use:
$scope.GTMcontainersAccount = response.data;
$scope.keys = Object.keys(response.data);
for(n in $scope.keys)
{
$scope.asim = $scope.keys[n];
console.log($scope.asim);
console.log(response.data[$scope.asim]);
}
This gives me this result:
So i have to write like:
console.log(response.data[$scope.asim][0].accountId);
But this gives me only row of "account2" not "account1"
Upvotes: 1
Views: 1389
Reputation: 32145
You need to use Object.keys()
to get the keys of your object, then for each key
get the relevant array
and loop over its items:
Object.keys(data).forEach(function(key) {
let accounts = data[key];
if (accounts && accounts.length) {
accounts.forEach(function(account) {
console.log(account);
});
}
});
Demo:
let data = {
"Account2": [{
"accountId": "17467****",
"containerId": "7454***",
"path": "accounts\/17467*****\/containers\/7454***",
}, {
"accountId": "17467****",
"containerId": "7519***",
"path": "accounts\/17467****\/containers\/7519***",
}],
"Account 1": [{
"accountId": "17661****",
"containerId": "7483***",
"path": "accounts\/17661****\/containers\/7483***",
}]
};
Object.keys(data).forEach(function(key) {
let accounts = data[key];
if (accounts && accounts.length) {
console.log(key+": ");
accounts.forEach(function(account) {
console.log(account);
});
}
});
Upvotes: 1