javascriptfunctionkey-valueobject-literalnew-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. 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. 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;
   }

Solution

  • The problem with your solution is that, keys[i + 1] could be equal to key, even though keys[i] does not.

    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]})}
        }, {})
    }