# 请教数组操作问题

Y_爱心_ct
• 6

``````const r = [
{
date: "2020-12",
regNum: "0"
},
{
date: "2021-1",
regNum: "1"
},
{
date: "2021-2",
regNum: "10"
}
]``````

``````const a = ["2020-12","2021-1","2021-2"]
const b = [0,1,10]``````

5 个回答
✓ 已被采纳

const a = r.map(o=>o.date)
const b = r.map(o=>Number(o.regNum))

a = r.map(o=>o.date)
b = r.map(o=>o.regNum)

``````function map(arr) {
var a = [];
var b = [];
for (var i = 0; i < arr.length; ++i) {
a.push(arr[i].date);
b.push(+arr[i].regNum);
}
return [a, b];
}
console.dir(map(r));``````

@lie5860 的就好，但是如果想在一个循环里完成，那就 @柯楠 的，或者下面这个 reduce 版本

``````const [a, b] = r.reduce((acc, { date, regNum }) => {
acc[0].push(date);
acc[1].push(parseInt(regNum, 10));
return acc;
}, [[], []]);``````

TS 版本：

``````type ArrayAttribute<T> = {
[K in keyof T]: Array<T[K]>
}

function gourpAttributes<T>(list: T[]) {
const result = {} as ArrayAttribute<T>

if (list.length === 0) return result

const [first, ...others] = list
const keys = Object.keys(first) as Array<keyof T>

keys.forEach(key => {
result[key] = [first[key]]
})

others.forEach(item => {
keys.forEach(key => {
result[key].push(item[key])
})
})

return result
}``````

JS 版本：

``````function gourpAttributes(list) {
const result = {}

if (list.length === 0) return result

const [first, ...others] = list
const keys = Object.keys(first)

keys.forEach(key => {
result[key] = [first[key]]
})

others.forEach(item => {
keys.forEach(key => {
result[key].push(item[key])
})
})

return result
}``````

``````const r = [
{
date: '2020-12',
regNum: '0'
},
{
date: '2021-1',
regNum: '1'
},
{
date: '2021-2',
regNum: '10'
}
]

const result = gourpAttributes(list)

console.log(result.date) // ['2020-12', '2021-1', '2021-2']
console.log(result.regNum) // [0, 1, 10]``````

###### 你尚未登录，登录后可以
• 和开发者交流问题的细节
• 关注并接收问题和回答的更新提醒
• 参与内容的编辑和改进，让解决方法与时俱进