如何创建一个从对象中省略 key/value 对的函数,并创建一个具有剩余属性和值的新对象?

How to create a function that omits key/value pairs from an object, and creates a new object with the remaining properties and values?

我一直在努力创建一个带有 source 和 keys 参数的 omit 函数,它检查源中的键,如果找到它们,将从源中省略这些属性,然后创建一个新的对象文字与源中剩余的 key/value 对。到目前为止,我一直没有成功,并且只能创建一个函数,该函数与使用在源中找到的键创建对象相反。谁能帮我弄清楚我错过了什么?将不胜感激!

function omit(source, keys) {
  var includedSource = {};
  for (var key in source) {
    for (var i = 0; i < keys.length; i++) {
      if (keys[i] !== key) {
        includedSource[key] = source[key];
        console.log('source[keys[i]]:', source[keys[i]]);
        console.log('includedSource:', includedSource);
      }
    }
  }
  return includedSource;
}

  function omit(source, keys) {
    var includedSource = {};
    for (var key in source) {
      for (var i = 0; i < keys.length; i++) {
        if (keys[i] === key) {
          includedSource[key] = source[key];
          console.log('source[keys[i]]:', source[keys[i]]);
          console.log('includedSource:', includedSource);
          }
        }
     }
     return includedSource;
   }

这是平面对象的简单实现。我不确定如果您的对象可能是嵌套的,将如何声明键,并且您希望提取一些 N 级嵌套 value/keys

const obj = {
  A: 1,
  B: 2,
  C: 3,
  D: 4
};

function omit(data, keys) {
  let result = {};

  for (let key in data) {
    if (keys.includes(key)) continue;

    result[key] = data[key];
  }

  return result;
}

console.log(omit(obj, ["A", "D"])) // {B: 2, C: 3}

您可以解构并休息一个新对象。

function omit(object, keys) {
    let _; // prevent to be global
    for (const key of keys) ({ [key]: _, ...object } = object);
    return object;
}

console.log(omit({ a: 1, b: 2, c: 3, d: 4 }, ['b', 'c']));

一种方法是使用 Object.entries() 并过滤掉具有不需要的键的条目,然后使用 Object.fromEntries() 从过滤后的条目创建新对象

const omit = (data, keys) => {
  return Object.fromEntries(
    Object.entries(data).filter(([k]) => !keys.includes(k))
  )
}


console.log(omit({ a:1,b:2,c:3,d:4}, ['a', 'b']))

转换为带有 Object.entries and Object.fromEntries and then filtering said entries with <Array>.filter 的条目可能效果很好:

const omit = (obj, keys) => Object.fromEntries(Object.entries(obj).filter(a=>!keys.includes(a[0])));

您的解决方案的问题在于,keys[i + 1] 可能等于 key,即使 keys[i] 不等于。

要更正您的代码,请应用以下更改。

function omit(source, keys) {
  var includedSource = {};
  for (var key in source) {
    if(!keys.includes(key)) { // <--- Change this
       includedSource[key] = source[key];
       console.log('source[keys[i]]:', source[keys[i]]);
       console.log('includedSource:', includedSource);
    }
  }
  return includedSource;
}

另一种方法,仅供娱乐。

function omit(source, keys) {
    return Object.keys(source).reduce((acc, curr) => {
        return {...acc, ...(keys.includes(curr) ? {} : {[curr]: source[curr]})}
    }, {})
}