我称为“国家”,其看起来像一个阵列:组或重新安排基于条件数组元素 - 的JavaScript
country=[
{
"name": "china",
"id": "country:china"
}, {
"name": "city1",
"id": "country:country1>city1"
}, {
"name": "city2",
"id": "country:country1>city2"
}, {
"name": "city3",
"id": "country:country1>city3"
}, {
"name": "korea",
"id": "country:korea"
}, {
"name": "australia",
"id": "country:australia"
}
]
我期待在重排/分组上述阵列:
countryResult = [ china, country1(city1, city2, city3), korea, australia]
我写了下面的代码,但是这并没有给我想要的结果:
$scope.countryInfo = function(itemData){
var countryResult = [];
for(var i=0; i<itemData.length; i++){
var countryItem = itemData[i];
if(countryItem.id.indexOf('>') > -1){ //Found city
var itemId = countryItem.id.substr(0, countryItem.id.indexOf('>'));
for(var j=0; j<$scope.countryData.length; j++){
if($scope.countryData[j].id == itemId){
var _parentChild = $scope.countryData[j].name + "(" + countryItem.name + ") ";
countryResult.push(_parentChild);
}
}
}
else{
countryResult.push(countryItem.name);
}
}
return countryResult;
}
结果是合作像这样 - [ china, country1(city1), country1(city2), country1(city3)), korea, australia]
请让我知道如何实现预期的数组结果。
编辑:我只是在寻找简化阵列[ china, country1(city1), country1(city2), country1(city3)), korea, australia]
到[ china, country1(city1, city2, city3), korea, australia]
我试图实施您的解决方案。在我可以加入元素之前,我需要用另一个文本替换临时图的关键字。在这样做的过程中,我迷失了方向。请让我知道如何将[china,country1(city1),country1(city2),country1(city3)),korea,australia [array1]澳大利亚] – Mustang