Iterate an array in javascript
I have a function in my controller to create a search filter.
The search parameter is obtained from the select box of my branch template.
The selected parameter is passed to the controller to see where the results are with that value.
The request result is returned in JSON format.
public function categoryAction(Request $request){
$em = $this->getDoctrine()->getManager();
$category = $request->request->get('category');
$contentCategory = $em->getRepository('PublicartelAppBundle:Content')->findByCategory($category);
$filterContent = new JsonResponse();
$filterContent->setData([
'category_result' => $contentCategory
]);
return $filterContent;
}
$('#selectCategory').on('change', function () {
var optionSelect = $(this).val();
$.post("{{path('playlist_category') }}", {category: optionSelect},
function (filterContent) {
var result = filterContent.category_result;
console.log(result);
}, 'json');
});
This is the return in the console:
[Object, object, object]
O: Object
1: Object
2: Object
length: 3
The number of items returned depends on the number of items found in that category.
If I do the following, you can iterate over each of the elements.
for (var content in filterContent.category_result){
console.log(content, filterContent.category_result[content]);
}
And return the following to the console:
0 Object {}
1 Object {}
2 Object {}
But I want to access the 'name' property for each object.
How can I tell I want to access the object's name property, or at least iterate over one at a time?
The problem is that the repository method findBy
returns Doctrine ArrayCollection
filled with the entity value. To translate it as valid JSON, you can iterate over it and translate it into a simple array, as shown in the Controller class:
$contentCategory = ....
$contents = array();
foreach($contentCategory as $elem)
$contents[] = array(
'name' => $elem->getName();
....
);
$filterContent = new JsonResponse();
$filterContent->setData([
'category_result' => $result
]);
return $filterContent;
You can also take into account the use of Serializer like http://jmsyst.com/libs/serializer
Hope for this help
You can register filterContent.category_result[content].name
if this is a matching property.
try this to see where "name" is:
for (var content in filterContent.category_result) {
console.log(content);
for (var i in filterContent.category_result[content]) {
console.log(filterContent.category_result[content][i]);
}
}