admin管理员组文章数量:1323716
create a json
array structure with key
using angularjs. I don't have any idea to how to push data to create json array structure with key
. I want to json array using below json data.
$scope.category = [{"id": 20, "name": "vegetable"},
{"id": 30, "name": "fruits"}];
$scope.data = [
{ "id" : 1,"name" : "tomato", "categoryId" : 20},
{ "id" : 2,"name" : "potato", "categoryId" : 20},
{ "id" : 3,"name" : "orange", "categoryId" : 30},
{ "id" : 4,"name" : "apple", "categoryId" : 30},
{ "id" : 4,"name" : "onion", "categoryId" : 20}];
for(var i=0; i<$scope.category.length; i++) {
for(var j=0; j<$scope.data.length; j++) {
if($scope.category[i].id === $scope.data[j].categoryId) {
}
}
}
I want output like this:
{
"vegetable" : [
{ "id" : 1, "name" : "tomato"},
{ "id" : 2, "name" : "potato"},
{ "id" : 3, "name" : "onion"},
],
"fruits" : [
{ "id" : 3, "name" : "orange"},
{ "id" : 4, "name" : "apple"}
]
}
create a json
array structure with key
using angularjs. I don't have any idea to how to push data to create json array structure with key
. I want to json array using below json data.
$scope.category = [{"id": 20, "name": "vegetable"},
{"id": 30, "name": "fruits"}];
$scope.data = [
{ "id" : 1,"name" : "tomato", "categoryId" : 20},
{ "id" : 2,"name" : "potato", "categoryId" : 20},
{ "id" : 3,"name" : "orange", "categoryId" : 30},
{ "id" : 4,"name" : "apple", "categoryId" : 30},
{ "id" : 4,"name" : "onion", "categoryId" : 20}];
for(var i=0; i<$scope.category.length; i++) {
for(var j=0; j<$scope.data.length; j++) {
if($scope.category[i].id === $scope.data[j].categoryId) {
}
}
}
I want output like this:
{
"vegetable" : [
{ "id" : 1, "name" : "tomato"},
{ "id" : 2, "name" : "potato"},
{ "id" : 3, "name" : "onion"},
],
"fruits" : [
{ "id" : 3, "name" : "orange"},
{ "id" : 4, "name" : "apple"}
]
}
Share
Improve this question
asked May 5, 2015 at 18:24
Satheesh NatarajanSatheesh Natarajan
4592 gold badges8 silver badges32 bronze badges
1 Answer
Reset to default 4To get your desired format you need to categoryId
from json before injecting it.
Code
$scope.myArray = [];
for(var i=0; i<$scope.category.length; i++) {
var array = [];
for(var j=0; j<$scope.data.length; j++) {
if($scope.category[i].id === $scope.data[j].categoryId) {
var index = array.push($scope.data[j]);
delete array[index-1].categoryId;
}
}
$scope.myArray[$scope.category[i].name] = array;
}
本文标签: javascriptcreate JSON array with key using AngularJSStack Overflow
版权声明:本文标题:javascript - create JSON array with key using AngularJS - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742126166a2421951.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论