在JavaScript中对对象数组的特定值运行自定义函数的最佳实践是什么?
假设我有两个函数和一个对象数组:在JavaScript中对对象数组的特定值运行自定义函数的最佳实践是什么?,javascript,Javascript,假设我有两个函数和一个对象数组: const f1 = (v) => { return v.toUpperCase(); } const f2 = (v) => { return v.toLowerCase(); } const arrayOfObjects = [ { v1: "foo", v2: "bar", v3: "foobar", }, {
const f1 = (v) => {
return v.toUpperCase();
}
const f2 = (v) => {
return v.toLowerCase();
}
const arrayOfObjects = [
{
v1: "foo",
v2: "bar",
v3: "foobar",
},
{
v1: "foo2",
v2: "bar2",
v3: "foobar2",
},
...
];
如何更新数组并在每个对象的v1
属性上运行f1
,在每个对象的v2
属性上运行f2
?
在我的real app中,我希望使用此方法格式化时间戳和用户名。您可以使用
map
方法和一些参数分解
const arrayofoobjects=[{“v1”:“foo”,“v2”:“bar”,“v3”:“foobar”},{“v1”:“foo2”,“v2”:“bar2”,“v3”:“foobar2”}]
常数f1=(v)=>v.toUpperCase();
常数f2=(v)=>v.toLowerCase();
常量结果=arrayOfObjects
.map({v1,v2,…rest})=>({
休息
v1:f1(v1),
v2:f2(v2)
}))
console.log(result)
ForEach将在您的阵列上循环
const f1=(v)=>{
return v.toUpperCase();
}
常数f2=(v)=>{
return v.toLowerCase();
}
常量数组对象=[
{
v1:“福”,
v2:“酒吧”,
v3:“foobar”,
},
{
v1:“foo2”,
v2:“bar2”,
v3:“foobar2”,
}
];
arrayOfObjects.forEach(e=>{
e、 v1=f1(e.v1);
e、 v2=f2(e.v2);
});
log(arrayOfObjects)
您可以使用一些正则表达式动态查找相关函数中的值
只需通过出现在键末尾的索引找到关联函数
const funcMap={
f1:(v)=>v.toUpperCase(),
f2:(v)=>v.toLowerCase(),
f3:(v)=>v.charAt(0).toUpperCase()+v.slice(1).toLowerCase()
};
常数arr=[
{v1:'foo',v2:'BAR',v3:'foobar'},
{v1:'foo2',v2:'BAR2',v3:'foobar2'}
];
常量进程=(arr)=>{
const funcEntries=Object.entries(funcMap);
返回arr.map(项目=>{
const itemEntries=Object.entries(项);
funcEntries.forEach(([funcKey,func])=>{
常数
[index]=funcKey.match(/\d+$/),
[itemKey,itemValue]=itemEntries
.find(([itemKey])=>
match(新的RegExp(`${index}$`));
item[itemKey]=func(itemValue);
});
退货项目;
});
};
控制台日志(进程(arr))代码>
.as控制台包装{top:0;max height:100%!important;}
循环遍历数组并对数组元素值运行函数?您尝试过哪些内容,哪些不起作用?您是否正在寻找forEach
,for…of
,map
?你想就地改变属性还是创建新对象?除非需要异步,否则我会使用forEach(),但idk如果这是“最佳实践”,就没有“最佳实践”这回事