У меня есть массив под названием «страна», которая выглядит следующим образом:Group или переставить элементы массива на основе состояния - 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;
}
в результате совместного ming up like this - [ china, country1(city1), country1(city2), country1(city3)), korea, australia]
Пожалуйста, дайте мне знать, как достичь ожидаемого результата массива.
EDIT: Я просто смотрю на упрощение массива [ 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] to [china, country1 (city1, city2, city3), korea, Австралия] – Mustang