简体   繁体   English

如何创建一个 function 省略 object 中的键/值对,并创建一个具有剩余属性和值的新 object?

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

I've been working on creating an omit function with a source and keys parameter, that checks for keys within the source, and if they are found, those properties are omitted from the source, then create a new object literal with the remaining key/value pairs within the source.我一直在努力创建一个带有 source 和 keys 参数的省略 function ,它检查源中的键,如果找到它们,则从源中省略这些属性,然后创建一个新的 object 文字和剩余的键/源中的值对。 So far, I've been unsuccessful, and only have been able to create a function that does the opposite of creating an object with the keys found within the source.到目前为止,我一直没有成功,只能创建一个 function,它与使用源中找到的密钥创建 object 相反。 Can anyone help figure out what I'm missing?谁能帮我弄清楚我错过了什么? It would be very appreciated!将不胜感激!

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;
   }

Here is a simple implementation with flat object.这是一个使用平面 object 的简单实现。 Im not sure how would keys be declared if your object might be nested, and you would expect to extract some of N level of nested value/keys如果您的 object 可能是嵌套的,我不确定如何声明键,并且您希望提取一些 N 级嵌套值/键

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}

You could destructure and rest for a new object.您可以解构 rest 以获得新的 object。

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

One approach is use Object.entries() and filter the entries out that have the unwanted keys then use Object.fromEntries() to create the new object from the filtered entries一种方法是使用Object.entries()并过滤掉具有不需要的密钥的条目,然后使用Object.fromEntries()从过滤后的条目中创建新的 object

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

Converting to entries with Object.entries and Object.fromEntries and then filtering said entries with <Array>.filter might work nicely:使用Object.entriesObject.fromEntries转换为条目,然后使用<Array>.filter过滤所述条目可能会很好地工作:

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

The problem with your solution is that, keys[i + 1] could be equal to key , even though keys[i] does not.您的解决方案的问题是, keys[i + 1]可能等于key ,即使keys[i]不等于。

To correct your code, apply following change.要更正您的代码,请应用以下更改。

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;
}

Another approach, just for fun.另一种方法,只是为了好玩。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 用于从两个对象属性创建键值对的函数 - Function to create key-value pairs from two object properties 如何创建一个函数,该函数接受一个对象并创建一个新的对象,其中值是键,键是值 - How to create a function that takes an object and creates a new object where the values are key and the keys are values 如何从连接的键值对创建 javascript object - How to create javascript object from concatenated key value pairs 如何从键值对数组创建对象? - How to create an object from an Array of key-value pairs? 将对象的属性和值转换为键值对数组 - Convert object's properties and values to array of key value pairs 使用来自其他对象的属性-值对创建一个新对象 - Create a new object with property-value pairs from an other object 如何访问使用 = 而不是键值对的 object 中的属性 - How to access the properties in an object that uses = instead of key value pairs 如何通过将另一个 object 的值作为键来创建新的 object? - How to create new object by making a value as key from another object? Javascript从该数组中附加对象并创建附加了对象键值对的新数组 - Javascript Append objects from this array and create new array with object key value pairs appended 如何创建仅包含数组中指定的键/值对的新对象? - How can I create a new object that only contains the key/value pairs specified in an array?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM