displaying nested json in ng-repeat - javascript

I seem to be having difficulty in grasping how to drill down to get to nested JSON and display it on a page using angular. For example I have the following JSON structure and I want to display the connectivity products under portfolio in an ng-repeat...
{
"addons": [
...
],
"attributes": [
...
],
"portfolios": [
{
"connectivity": [
{
"product-1": {
"label": "product-1",
"description": "Description in here"
}
},
{
"product-2": {
"label": "product-2",
"description": "Description in here"
}
}
]
}
]
}
So far I have tried it two different ways.
$scope.listOfProducts = allProducts.data.portfolios.connectivity;
and in the ng-repeat
ng-repeat='product in listOfProducts.portfolios.connectivity'
What would be the correct way to loop through and display the 'connectivity' products in a ng-repeat? Thanks
EDIT:
I've changed the JSON to this structure...
{
"addons": [
...
],
"attributes": [
...
],
"portfolios": [
{
"connectivity": [
{
"label": "product-1",
"description": "Description in here"
},
{
"label": "product-2",
"description": "Description in here"
}
]
}
]
But I still can't seem to get ng-repeat to display the products in connectivity.
$scope.listOfProducts = allProducts.data.portfolios.connectivity

Since listOfProducts is already set to the connectivity array, you would just ng-repeat="product in listOfProducts"
<div ng-repeat="product in listOfProducts">
{{product.label}}
</div>
Edit: Well, your array is sort of irregular, since you're creating a property called product-[index] for each item. Do you have control of the data which is returned? Your array should just have the objects, like:
"connectivity": [
{
"label": "product-1",
"description": "Description in here"
},
{
"label": "product-2",
"description": "Description in here"
}
]

Related

is it possible to retrieve and print the data from a json object inside json array without using any index values and specific keys

[
{
"id": "628ba44f5a6de600071d16fa",
"#baseType": "LogicalResource",
"isBundle": false,
"isMNP": false,
"businessType": [],
"category": [
{
"id": "628ba3ef5a6de600071d165f",
"name": "Starterpack2",
"description": "Starterpack2",
"code": "RC17",
"version": 2
}}]
now i need to check and print the JSON Object inside the JSON Array if category is present then it should print and in future if category is changed according to that if we pass parameter the output should print we don't hard code the code
i have tried by using key values it is coming but if the key value changes it is not printing the object
EX:-
[
{
"id": "628ba44f5a6de600071d16fa",
"#baseType": "LogicalResource",
"isBundle": false,
"isMNP": false,
"businessType": [],
"category": [
{
"id": "628ba3ef5a6de600071d165f",
"name": "Starterpack2",
"description": "Starterpack2",
"code": "RC17",
"version": 2
}}]
in the above code i have printed category object but if category changed to categories it is not printing so i want a code which can read the code and based on parameters user giving it should be print the output
Try this.
For Example:
let a = [{"id": "628ba44f5a6de600071d16fa","category": [
{
"id": "628ba3ef5a6de600071d165f",
"name": "Starterpack2",
"description": "Starterpack2",
"code": "RC17",
"version": 2
}]}]
function print (values){return (a[0][`${values}`])}
//now just pass any name like "category" or in future "categories"
print("category") //this will retrun the array.
Now modify with your requirements.
It seems you want to get the value of the key(that can be parameterized).
const jsonArray = [
{
"id": "628ba44f5a6de600071d16fa",
"#baseType": "LogicalResource",
"isBundle": false,
"isMNP": false,
"businessType": [],
"category": [
{
"id": "628ba3ef5a6de600071d165f",
"name": "Starterpack2",
"description": "Starterpack2",
"code": "RC17",
"version": 2
}
]
}
];
const parameter = "category";
const result = jsonArray.find(({ [parameter]: value }) => value);
if (result) {
console.log(result);
} else {
console.log(`No object found with ${parameter}`);
}
If this is not what you are looking for, then please add your code snippet for better understanding.

Update a field in nested array of objects containing another array of objects in mogoDb (JavaScript)

I have the following structure of Student collection in MongoDb:
{
"_id": "st1",
"student_courses": [
{
"_id": "c1",
"course_name": "Node",
"image": [
{
"_id": "c1img1",
"image": "img1.jpeg"
}
]
},{
"_id": "c2",
"course_name": "React",
"image": [
{
"_id": "c2img2",
"image": "img2.jpeg"
}
]
}
],
}
Now, I want to update the image name of img1.jpeg in all the documents that have same image name. So what I am doing is this:
Student.updateMany(
{ "student_courses._id": "c1"},
{
$set: {
"student_courses.$.course_name": "Node Crash Course",
"student_courses.$.image[0].image": complete_image_name,
},
}
);
Unexpectedly, this is updating course_name field but image. I have tried using $ positional argument instead of [0] but got the error Too many positional arguments ...... I don't know how to do that. My expected output should look like this:
{
"_id": "st1",
"student_courses": [
{
"_id": "c1",
"course_name": "Node Crash Course",
"image": [
{
"_id": "c1img1",
"image": "complete_image_name.jpeg"
}
]
},
:::::::::::::::::::
:::::::::::::::::::
],
}
{
"_id": "st2",
"student_courses": [
{
"_id": "c1",
"course_name": "Node Crash Course",
"image": [
{
"_id": "c1img1",
"image": "complete_image_name.jpeg"
}
]
},
:::::::::::::::::::
:::::::::::::::::::
],
}
Moreover, I have implemented almost every method posted in similar questions. Thanks in advance for any help.
Try to change the way you are referring to the first element in the array:
Student.updateMany(
{ "student_courses._id": "c1"},
{
$set: {
"student_courses.$.course_name": "Node Crash Course",
"student_courses.$.image.0.image": complete_image_name,
},
}
);

Extract information from json

So I have the following object from my controller, which has a name, a list of beans and a list of operations:
{
"name": "Charge",
"beans": [
],
"operations": [
{
"name": "getSize",
"returnType": "java.lang.Integer",
"description": "empty description",
"parameters": [
]
},
{
"name": "truncate",
"returnType": "java.lang.Void",
"description": "empty description",
"parameters": [
]
},
{
"name": "count",
"returnType": "java.lang.Integer",
"description": "empty description",
"parameters": [
{
"name": "javaCode",
"type": "java.lang.String",
"value": null
}
]
},
{
"name": "update",
"returnType": "java.lang.Integer",
"description": "empty description",
"parameters": [
{
"name": "javaSelectCode",
"type": "java.lang.String",
"value": null
},
{
"name": "javaUpdateCode",
"type": "java.lang.String",
"value": null
}
]
},
{
"name": "delete",
"returnType": "java.lang.Integer",
"description": "empty description",
"parameters": [
{
"name": "javaCode",
"type": "java.lang.String",
"value": null
}
]
},
{
"name": "dump",
"returnType": "java.lang.Void",
"description": "empty description",
"parameters": [
{
"name": "javaSelectCode",
"type": "java.lang.String",
"value": null
},
{
"name": "destinationPath",
"type": "java.lang.String",
"value": null
}
]
},
{
"name": "select",
"returnType": "java.lang.String",
"description": "empty description",
"parameters": [
{
"name": "javaCode",
"type": "java.lang.String",
"value": null
}
]
}
],
"$$hashKey": "object:620"
}
Basically I want to display all the operations from this object in a dropdown menu.
So I was thinking of having something like:
<div ng-repeat="operation in object.operations">
{{operation.name}}
</div>
Except the code above doesn't display anything on the screen, no errors in the console, nothing.
Any help would be much appreciated!
EDIT:
Javascript service:
app.controller('selectAll', ['$http', '$scope' , '$rootScope', function ($http, $scope, $rootScope) {
$scope.response;
$scope.operations;
$rootScope.$on("invokeSelectAll", function(){
$scope.invokeSelectAll();
});
$scope.invokeSelectAll = function(){
$scope.response = $http.post('/invoke/selectAll/', $rootScope.dataObj);
$scope.object = JSON.stringify($rootScope.object);
console.log(" object operation from selectAll " + $scope.object);
$scope.response.then(function(data) {
$scope.responses = data.data ? data.data : "Select Operation not supported on this bean";
});
}
}]);
Screenshot of dev console:
https://imgur.com/a/8WAAL
Use JSON.stringify() to create a JSON string from a JavaScript object.
Use JSON.parse() to parse a JSON string to a JavaScript object.
In your case, you need to use JSON.parse() because you get a JSON string from the server and want to parse it to a JavaScript object.
$scope.object = JSON.parse($rootScope.object);
you are using JSON.stringify which is used to change javascript object to string and store it as a string only.
You should Parse the data with JSON.parse(), and the data becomes a JavaScript object. and you can easily use that in ng-repeat.
Try it ,It will work fine

Searching through JSON object

I am trying to search through a json object to select some values. For example I have a variable with the value 'product-2' and I want to look through the json object and return the attributes array of 'product-2'
{
"attributes": [
...
],
"portfolio": [
{
"conn": [
{
"product": "product-1",
"description": "Description in here",
"attributes": [
"OriginPostcode",
"Size",
"Bandwidth"
],
},
{
"product": "product-2",
"description": "Description in here"
"attributes": [
"OriginPostcode",
"Size",
"Bandwidth"
],
}
]
}
]
Could anyone tell me how I can achieve this? Thank you
EDIT:
As per Pramods request - I was working with the following js (although its really wrong I am sure)
$scope.productAttributes = [];
$scope.getProductDetails = function (product_id) {
console.log(product_id);
//search trough json
angular.forEach($scope.listOfProducts.product_id, function(value, key) {
// I was thinking I could loop through the json and when I find the matching product, then push its attributes into an array?
// if (key === enteredValue) {
// $scope.productAttributes.push({atribute: key});
// }
});
};
EDIT No.2
The JSON structure has changed
Use a filter to destructure the array.
In my example I use a filter within a Controller. This should probably be done in a service or a view. For brevity I used the filter in a controller.
The filter expression essentially says, return the first object in the array with a property 'product' that is 'product-2'
var app = angular.module('app', []).controller('MyController', MyController);
MyController.$inject = ['$filter'];
function MyController($filter) {
var data = [
{
"product": "product-1",
"description": "Description in here",
"attributes": [
"OriginPostcode",
"Size",
"Bandwidth"
],
},
{
"product": "product-2",
"description": "Description in here",
"attributes": [
"OriginPostcode",
"Size",
"Bandwidth"
],
}
]
this.product = $filter('filter')(data, {product: "product-2"})[0];
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app">
<div ng-controller="MyController as vm">
Product-2: {{vm.product}}
</div>
</div>
Well, if you don't know how product-2 will be nested and you actually need to search for it, then you need to do a recursive search. A recursive function is a function that calls itself.
This means that you iterate over each of the keys, and if the key is an object, call the recursive function on that key as well, until the key you want is found.
Here is a similar question, with a few algorithms provided for doing recursive search on a JSON structure in JavaScript: traversing through JSON string to inner levels using recursive function
I think your JSON is wrong , So please correct it
Correct JSON
{
"attributes": [],
"portfolio": [
{
"conn": [
{
"product-1": {
"label": "product-1",
"description": "Description in here",
"attributes": [
"OriginPostcode",
"Size",
"Bandwidth"
],
}
},
{
"product-2": {
"label": "product-2",
"description": "Description in here",
"attributes": [
"OriginPostcode",
"Size",
"Bandwidth"
],
}
}
]
}
]
}
And to parse above json and return product information following is the code
$(document).ready(function() {
$.each(dict['portfolio'][0], function(key, list){
$.each(list, function(index, value){
$.each(value, function(product, info){
if (product == "product-2"){
answer = {}
answer[product] = info;
return JSON.stringify(answer);
}
});
});
});
});
Fiddle link :-
http://fiddle.jshell.net/2t8uknkc/

ng-repeat not pushing data

I'm using ng-repeat directive to list a set of JSON data of the format
$scope.result=[
{
"id": 84,
"resource": {
"id": 3,
"name": "Resource Planning",
"description": "test"
},
"activity": {
"id": 6,
"name": "Activity Planning",
"description": "test"
}
}
]
My usage of ng-repeat is like this..
<div ng-repet="data in result">{{data.resource.name}} {{data.activity.name}}</div>
I'm able to display the name ie., "Resouce Planning" and "Activity Planning".
But I can't push the data if I'm doing like this
$scope.result.push({resource.name:result.resource.name,activity.name:result.activity.name})
from the controller.
Is there any way to push the name which is inside the object. And to display/list the same using ng-repeat?
Thanks
I don't really understand the question, but that's not how you build your javascript object. It should be something like:
$scope.result.push({
resource: {
name: result.resource.name
},
activity: {
name: result.activity.name
}
})

Categories