gpt4 book ai didi

javascript - AngularJS 和 JSON 数组

转载 作者:行者123 更新时间:2023-11-30 16:05:10 27 4
gpt4 key购买 nike

我正在尝试使用 AngularJS 过滤器(例如 $filter)按如下所示安排现有的 JSON 数组,但它失败了。

 {
{
name: "name 1",
label: "A",
},
{
name: "name 2",
label: "A",
},
{
name: "name 3",
label: "B",
},
{
name: "name 4",
label: "B",
},
{
name: "name 5",
label: "B",
},
{
name: "name 6",
label: "C",
},
{
name: "name 7",
label: "C",
},
{
name: "name 8",
label: "C",
},
{
name: "name 9",
label: "D",
}
}

我想要的是将这个数组安排到下面的新数组中。

{
"A" : {
{
name: "name 1",
label: "A",
},
{
name: "name 2",
label: "A",
},
},
"B" : {
{
name: "name 3",
label: "B",
},
{
name: "name 4",
label: "B",
},
{
name: "name 5",
label: "B",
},
},
"C" : {
{
name: "name 6",
label: "C",
},
{
name: "name 7",
label: "C",
},
{
name: "name 8",
label: "C",
},
},
"D" : {
{
name: "name 9",
label: "D",
}
}
}

如何使用 angularJS 获取新数组?

最佳答案

如果您使用的是 lodash ,您可以为此使用 _.groupBy 函数:

var grouppedArray = _.groupBy(myArray, function(i){
return i.label;
})

要仅提取标签,您可以像这样

var uniqueLables = [];
angular.forEach(myArray, function(obj){
if(uniqueLables.indexOf(obj.label) == -1) uniqueLables.push(obj.label)
})

关于javascript - AngularJS 和 JSON 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37143566/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com