功能的方法:
let arr = [
{_id: '1', description: 'a', location: 'us'},
{_id: '2', description: 'b', location: 'us'},
{_id: '3', description: 'c', location: 'tw'}
]
let result = Object.entries(arr.reduce((h, {_id, description, location: l}) =>
Object.assign(h, {[l]: [...(h[l] || []), {_id, description}]})
, {})).map(([l, d]) => ({location: l, data: d}))
console.log(result)
或者更可讀的辦法:
let arr = [
{_id: '1', description: 'a', location: 'us'},
{_id: '2', description: 'b', location: 'us'},
{_id: '3', description: 'c', location: 'tw'}
]
let dict = arr.reduce((dict, {_id, description, location}) => {
dict[location] = dict[location] || []
dict[location].push({_id, description})
return dict
}, {})
let result = Object.entries(dict).map(([l, d]) => ({location: l, data: d}))
console.log(result)
能否請你加你已經嘗試到現在什麼...你可以在這裏回答,但讓我們知道你的嘗試... –
JSON我用於數據交換的*文本符號*。 [(More here。)](http://stackoverflow.com/a/2904181/157247)如果你正在處理JavaScript源代碼,而不是處理*字符串*,那麼你並沒有處理JSON。 (如果*爲*爲JSON,則爲無效;在JSON中,屬性名稱必須用引號引起來。) –
努力解決該問題。 **如果**你被卡住了,告訴我們你試過什麼,告訴我們你有什麼問題,等等。現在這是「寫給我」,這是不適合SO的。 –