功能的方法:
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的。 –