例如我有这个数组:
const arr = [
{val1: '123', text: 'not a num', new:'123.34'},
{val1: '123', text: 'not a number', new:'123.34'},
{val1: '123', text: 'yahoo', new:'123.34'}
]
我想键转换val1
和新成number
,
所以我创建了这个函数:
const convertToNumbers = (arr: Array<{ unknown }>, keys: Array<string>) => {
return arr.map((val) => {
keys.map((k) => {
console.log(val[k]);
return (val[k] = +val[k]);
});
});
};
预期结果应该是这样的:
const result = [
{val1: 123, text: 'not a num', new:123.34},
{val1: 123, text: 'not a number', new:123.34},
{val1: 123, text: 'yahoo', new:123.34}
]
该函数将接受两个Array(第一个参数是Array本身,第二个参数包含要转换为数字的键)。
有办法解决我的问题吗?
您可以映射新对象并转换所需的键。
const
array = [{ val1: '1,234', text: 'not a num', new:'123.34' }, { val1: '123', text: 'not a number', new:'123.34' }, { val1: '123', text: 'yahoo', new:'123.34' }],
keys = ['val1', 'new'],
result = array.map(object => ({
...object,
...Object.fromEntries(keys.map(key => [key, +object[key].replace(/[^\d.]/g, '')]))
}));
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句