javascript 使用 AngularJS 创建带键的 JSON 数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30060515/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
create JSON array with key using AngularJS
提问by Satheesh Natarajan
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.
使用 angularjs创建一个json
数组结构key
。我不知道如何推送数据以使用 .json 创建 json 数组结构key
。我想使用下面的 json 数据来 json 数组。
$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"}
]
}
回答by Pankaj Parkar
To get your desired format you need to categoryId
from json before injecting it.
要获得所需的格式,您需要categoryId
在注入之前从 json 中获取。
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;
}