2017-12-03 55 views
0

我的位置列表:如何在Javascript中重組對象?

[ 
{ 
    "id": 1, 
    "name": "Location 1", 
    "city": { 
     "id": 7, 
     "name": "Phoenix", 
    } 
}, 
{ 
    "id": 2, 
    "name": "Location 2", 
    "city": { 
     "id": 7, 
     "name": "Phoenix", 
    } 
}, 
{ 
    "id": 3, 
    "name": "Location 3", 
    "city": { 
     "id": 11, 
     "name": "Los Angeles", 
    } 
} 
] 

出的,我想創造城市的數組,每個城市有來自城市的位置。

結果舉例:

[ 
    { 
     "id": 7, 
     "name": "Phoenix", 
     "locations": [ 
       // location objects from Phoenix (Location 1 and Location 2) 
      { 
       "id": 1, 
       "name": "Location 1", 
       "city": { 
        "id": 7, 
        "name": "Phoenix", 
       } 
      }, 
      { 
       "id": 2, 
       "name": "Location 2", 
       "city": { 
        "id": 7, 
        "name": "Phoenix", 
        } 
       } 
     ] 
    }, 
    { 
     "id": 11, 
     "name": "Los Angeles", 
     "locations": [ 
       // location objects from Los Angeles (Location 3) 
      { 
       "id": 3, 
       "name": "Location 3", 
       "city": { 
        "id": 11, 
        "name": "Los Angeles", 
       } 
      } 
     ] 
    } 
] 

我一直在使用.map().filter()獲得唯一值的城市陣列嘗試。它並沒有返回整個cityreturn item.city)的唯一,不同的值,所以我只使用name屬性(return item.city.name),因爲我並不真正在意城市ID。我的獨特的城市名稱的數組:

var cities = data.map(function (item) { 
    return item.city.name; 
}).filter(function (value, index, self) { 
    return self.indexOf(value) === index; 
}); 

現在我卡在構建陣列將列出位置爲每個城市的屬性。預先感謝您...

+0

您的預計結果無效。 「位置」應該是一個對象還是一個數組? –

+0

@Mark_M'locations'應該是一個對象數組。 – TommyZG

回答

1

我會首先創建一個對象,其中鍵設置爲城市的id。然後,如果您需要數組中的這些對象,則只需通過鍵調用映射。例如創建鎖定以ID對象:

var arr = [{"id": 1,"name": "Location 1","city": {"id": 7,"name": "Phoenix",}},{"id": 2,"name": "Location 2","city": {"id": 7,"name": "Phoenix",}},{"id": 3,"name": "Location 3","city": {"id": 11,"name": "Los Angeles",}}] 
 

 
var obj = arr.reduce((a, c) => { 
 
    if (a[c.city.id]) a[c.city.id].push(c) 
 
    else a[c.city.id] = [c] 
 
    return a 
 
}, {}) 
 

 
console.log(obj)

現在你有一個乾淨的對象,如果你想要一個數組只需添加一個地圖上的按鍵:

var arr = [{"id": 1,"name": "Location 1","city": {"id": 7,"name": "Phoenix",}},{"id": 2,"name": "Location 2","city": {"id": 7,"name": "Phoenix",}},{"id": 3,"name": "Location 3","city": {"id": 11,"name": "Los Angeles",}}] 
 

 
var obj = arr.reduce((a, c) => { 
 
    if (a[c.city.id]) a[c.city.id].locations.push(c) 
 
    else a[c.city.id] = {name: c.city.name, locations:[c]} 
 
    return a 
 
}, {}) 
 

 
var arr_version = Object.keys(obj).map(k => Object.assign({id: k}, obj[k])) 
 

 
console.log(arr_version)

+0

謝謝,這正是我一直在努力做到的。我將嘗試破譯此解決方案的每一步,以更好地理解它。 – TommyZG

相關問題