In javascript ES6, is there a method that can extract specified properties from an object to form a new object?

for example:

var obj = {a: 1, b: 2, c: 3, d: 4}
Object.certainFunction (obj, ["a","b"])
= > {a: 1, b: 2}

method like this?

Mar.17,2021

No, you need to write your own extension.


function certainFunction(obj, keys) {
  return keys.reduce((result, key) => {
    if (obj.hasOwnProperty(key)) {
      result[key] = obj[key];
    }
    
    return result;
  }, {});
}

var obj = { a: 1, b: 2, c: 3, d: 4 };
certainFunction(obj, ['a', 'b']);
Menu