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

问题描述

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

所以:

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

应归一化为:

const foo = {
  first: null,fourth: null,}

现在以下示例有效:

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: '',}

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

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

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

可以这样做吗?

解决方法

另一种方法遍历keys参数数组。没有必要遍历对象中的所有键,而仅遍历所需的键

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']));

,

怎么样?

请参考norm中的键,将新映射返回为 null (如果要进行标准化),否则为空字符串本身。

const foo = {
  first: '',},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}
,

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

const foo = {
  first: '',}

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: '',}


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,'third']));

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...