简体   繁体   中英

Omitting spread array from object

I have a function:

const mergedPartOfStateWithCurrentSearchValues = (object, valuesToOmit) => {
  const {...valuesToOmit, ...rest } = object;
  return rest;
};

The first argument is an object. The second argument is an array of string values to omit from the object. I'm trying to return the rest. So this actually doesn't work like that. I've tried to use lodash as well:

const mergedPartOfStateWithCurrentSearchValues = (object, valuesToOmit) => {
  const filteredObject = pickBy(object, function (value, key) {
    return !valuesToOmit.includes(key)
  })
  return filteredObject;
};

And it doesn't work as well. I'm running out of ideas. How can I do what I want to and keeping the generic nature of this function?

You could take the entries of your object using Object.entries() and then filter out the entries which keys appear in your valuesToOmit array by using the .includes() and .filter() methods. Then, you can use Object.fromEntries() to build an object from these filtered entries:

 const object = {a: 1, b: 2, c: 3}; const valuesToOmit = ['a', 'c'] const mergedPartOfStateWithCurrentSearchValues = (object, valuesToOmit) => { return Object.fromEntries( Object.entries(object).filter(([k]) => !valuesToOmit.includes(k)) ); } const res = mergedPartOfStateWithCurrentSearchValues(object, valuesToOmit); console.log(res);

If you can't support Object.fromEntries() , you could map the entries returned by Object.entries() to objects, and then merge them into a larger object using Object.assign() :

 const object = {a: 1, b: 2, c: 3}; const valuesToOmit = ['a', 'c'] const mergedPartOfStateWithCurrentSearchValues = (object, valuesToOmit) => { return Object.assign( ...Object.entries(object).filter(([k]) => !valuesToOmit.includes(k)).map(([k, v]) => ({[k]: v})) ); } const res = mergedPartOfStateWithCurrentSearchValues(object, valuesToOmit); console.log(res);

Note : You can improve the efficiency of the above method by making valuesToOmit an ES6 Set , and then using the .has() method rather than the .includes() method.

You could reduce the array and get only an object without wanted keys.

It works by removing a single key from the object in each loop by using a computed property and assigning to new variable name underscore, which is not used anymore and rest in object destructuring .

As result you get an object with without unwanted keys.

 const subSet = (object, without) => without.reduce((o, k) => ({ [k]: _, ...o } = o, o), object); console.log(subSet({ a: 1, b: 2, c: 3 }, ['a', 'c']));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM