以不可变的方式为特定键更改对象属性

Change objects properties in an immutable way for specific keys

如果预定义键的值是空字符串,那么我想将其更改为空值。

所以:

const foo = {
  first: '',
  second: 'bar',
  third: '',
  fourth: '',
  fifth: '',
}

应归一化为:

const foo = {
  first: null,
  second: 'bar',
  third: '',
  fourth: null,
  fifth: '',
}

现在下面的例子有效了:

const normalize = (payload, keys) => {
  const clone = { ...payload }
  Object.entries(payload).forEach(([key, value]) => {
    if (keys.includes(key) && value === '') {
      clone[key] = null;
    }
  });
  return clone;
}

const foo = {
  first: '',
  second: 'bar',
  third: '',
  fourth: '',
  fifth: '',
}

console.log(normalize(foo, ['first', 'third']));

但是 'clone' 变量不是那么精明。

现在有一个常用的方法就是使用Object.assign()

可以这样做吗?

这个怎么样?

将您在 norm、return 新映射中的键称为 null 如果要 规范化 否则空字符串本身。

const foo = {
  first: '',
  second: 'bar',
  third: '',
  fourth: '',
  fifth: '',
}, norm = ['third', 'fifth'];

const normalize = (payload, keys) => {
    return keys.reduce((a, k) => a[k] === "" && (a[k] = null) || a, {...payload})
}

输出:

const norm = ['third', 'fifth'];
normalize(foo, norm)

{first: "", second: "bar", third: null, fourth: "", fifth: null}

循环键参数数组的替代方法。遍历对象中的所有键没有意义,而只是需要的键

const normalize = (payload, keys) => {
  return keys.reduce((a, k) => {
    (a[k] === '') && (a[k] = null)
    return a;
  }, { ...payload })
}

const foo = {
  first: '',
  second: 'bar',
  third: '',
  fourth: '',
  fifth: '',
}

console.log(normalize(foo, ['first', 'third']));

您可以使用迭代 for...in 并检查密钥是否与 some()

匹配

const foo = {
  first: '',
  second: 'bar',
  third: '',
  fourth: '',
  fifth: '',
}

const normalize = ({...obj}, arr) => {
  for (let key in obj) {
    if(arr.some(k => k === key)) {
      obj[key] = null;
    }
  }

  return obj;
}

console.log(normalize(foo, ['third', 'fifth']));

为什么不遍历数组并改变对象

const foo = {
  first: '',
  second: 'bar',
  third: '',
  fourth: '',
  fifth: '',
}


function normalize(obj, arr) {
const newObj={...obj}
  for (let i = 0; i < arr.length; i++) {
    newObj[arr[i]] = null;
  }
  return newObj;
}
console.log(normalize(foo, ['first', 'third']));