基于对象道具的条件传播

Condition Spread based on Object props

我正在寻找删除空或空道具的方法,在我的示例 obj2 上,我想避免复制 birthPlace 属性 或任何其他空道具。

const obj1 = { firstName: 'Foo', age: 22 };

const obj2 = { lastName: 'Bar', gender: 'M', birthPlace: '' };

const newObj = { ...obj1, ...obj2 };

想要的结果:

{firstName: 'Foo', age: 22, lastName: 'Bar', gender: 'M'}

是否可以在 javascript 中使用传播运算符使用条件对象道具?

const updateUserObj = {
  ...(obj1 !== check here<hasPropEmpty> && obj2)
}

它没有 shorthand,但您可以轻松编写一个函数来过滤掉这些属性。

function nonEmptyProps(obj) {
  return Object.fromEntries(Object.entries(obj).filter(([k, v]) => v !== null && v !== ''));
}

const obj1 = { firstName: 'Foo', age: 22 };

const obj2 = { lastName: 'Bar', gender: 'M', birthPlace: '' };

const newObj = {...nonEmptyProps(obj1), ...nonEmptyProps(obj2)};
console.log(newObj);

使用 Object#entries you get the key-value pairs of an object, then, using Array#filter you iterate over these pairs to filter out the ones with empty values. Then, using Object#fromEntries 将结果对构造回一个对象。

const filterProps = (obj = {}) => 
  Object.fromEntries(
    Object.entries(obj).filter(([key, value]) => 
      value !== null && value !== undefined && value !== ''
    )
  );

const obj1 = { firstName: 'Foo', age: 22 };
const obj2 = { lastName: 'Bar', gender: 'M', birthPlace: '' };

const newObj = { ...filterProps(obj1), ...filterProps(obj2) };

console.log(newObj);