我稱爲「國家」,其看起來像一個陣列:組或重新安排基於條件數組元素 - 的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