gpt4 book ai didi

javascript - 在 AngularJs 中转换 JSON 对象

转载 作者:行者123 更新时间:2023-11-27 23:54:39 25 4
gpt4 key购买 nike

有没有办法使用 Angular 转换这个 JSON 对象?我需要将 JSON 对象从这种格式转换为:

    $scope.TestJson = {
"filters": [
{
"dataPropertyID": "VoidType",
"label": "Homeless"
},
{
"dataPropertyID": "VoidType",
"label": "Mainstream"
},
{
"dataPropertyID": "PropertyType",
"label": "Flat"
},
{
"dataPropertyID": "PropertyType",
"label": "Cottage"
}
]
}

采用这种格式:

    $scope.NewTestJson = {
"filters": [
{
"dataPropertyID": "VoidType",
"label":[ "Homeless","Mainstream"]
},
{
"dataPropertyID": "PropertyType",
"label":[ "Flat", "Cottage"]
}
]
}

最佳答案

我认为这更像是一个 JavaScript 问题。尽管如此:

$scope.NewTestJson = {
filters: [];
};

// Do something for all (old) filter items
$scope.TestJson.filters.forEach(function(filter) {
// Try to get the existing (new) filter
var newFilter = $scope.NewTestJson.filters.filter(function(newFilter) {
return newFilter.dataPropertyID === filter.dataPropertyID;
}).shift();

// If the new filter does not exist, create it
if (!newFilter) {
newFilter = {
dataPropertyID: filter.dataPropertyID,
label: []
};
$scope.NewTestJson.filters.push(newFilter);
}

// Finally, add the old filter label to the new filter
newFilter.label.push(filter.label);
});

关于javascript - 在 AngularJs 中转换 JSON 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32372895/

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