Object.entries(obj).reduce((acc, [key, value]) => {
if (someCondition(key, value)) {
acc[key] = value;
}
return acc;
}, {});
Object.entries(obj)
.filter(([key, value]) => someCondition(key, value))
.reduce((acc, [key, value]) => {
acc[key] = value;
return acc;
}, {});上面的两个块做了相同的事情:创建一个obj的副本,其中删除了一些基于someCondition的属性。
选择哪一种方式?为什么?
发布于 2018-04-15 13:38:44
要看情况而定。
对于第一种情况--有条件的reduce --您将只循环一次数据集。
第二个例子给出了两个循环(第二个工作在有限的数据集上),但是代码的可读性要高得多,并且操作是分开的(过滤/修改数据)。
发布于 2018-04-15 13:40:47
我更喜欢完全强制的方法
function filterProperties(obj, predicate) {
const res = {};
for (const key in obj) {
const val = obj[key];
if (predicate(key, var))
res[key] = val;
}
return res;
}或者全功能方法
function filterProperties(obj, predicate) {
return fromEntries(Object.entries(obj).filter(entry => predicate(...entry)));
}
function fromEntries(entries) {
const res = {};
for (const [key, val] of entries) // using `reduce` is not much of an advantage here
res[key] = val;
return res;
}https://stackoverflow.com/questions/49842511
复制相似问题