请教数组操作问题
现有数组
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]
回答:
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]
以上是 请教数组操作问题 的全部内容, 来源链接: utcz.com/p/936560.html