Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rest operator - dynamically remove elements to get rest

Tags:

javascript

I was wondering if there's an option to acheive effect as below

const x = {
  a:1,
  b:2,
  c:3,
  d:4,
  e:5
}

const y = ['a', 'b'];

To get only c,d,e I can easily go with rest operator:

const { a, b, ...rest} = x;

and rest contain 3 keys

The code below is not working - but is there a way to do it somehow with rest operator?

const { ...y, ...rest} = x;

To have in rest those 3 keys so if i would define

const y = ['a','b','c']

then I would have 2 keys in rest?

like image 426
Mateusz Lewandowski Avatar asked Jun 29 '26 06:06

Mateusz Lewandowski


2 Answers

Curried ES6 partial implementation of _.omit (and, for good measure, _.pick):

const data = { a: 1, b: 2, c: 3, d: 4, e: 5 }
const someKeys = ['a', 'b', 'c']
  
const pick = keys => o =>
  keys.reduce(
    (acc, key) => Object.assign(acc, { [key]: o[key] }),
    {}
  )
  
console.log(
  `pick [${someKeys}]:`,
  pick(someKeys)(data)
)
// -> { a: 1, b: 2, c: 3 }
  
const omit = keys => o => 
  pick(Object.keys(o).filter(k => !(keys.includes(k))))(o)

console.log(
  `omit [${someKeys}]:`,
  omit(someKeys)(data)
)
// -> { d: 4, e: 5 }

const fromEntries = entries =>
  entries.reduce(
    (acc, [k, v]) => Object.assign(acc, { [k]: v }),
    {}
  )
  
console.log(
  'fromEntries:',
  fromEntries(Object.entries(data))
)
// -> { a: 1, b: 2, c: 3, d: 4, e: 5 }

I rewrote omit and pick to be more efficient, and neither depends on fromEntries any more. I left fromEntries in, anyway, since it can be pretty useful (to turn the output of Object.entries() into an object). Object.fromEntries() is a stage 3 proposal, so will hopefully be widely supported at some point, but this version may be useful in the meantime.

like image 180
tex Avatar answered Jun 30 '26 21:06

tex


Probably not as elegant as you would want, but if you want to dynamically get the keys not in an array you can use:

const x = {
  a:1,
  b:2,
  c:3,
  d:4,
  e:5
}

const y = ['a', 'b', 'c'];

const rest = Object.keys(x).filter(key => y.indexOf(key) === -1);

console.log(rest);

Basically we get the keys for that object and filter those not present in the y array.

like image 27
rubentd Avatar answered Jun 30 '26 21:06

rubentd



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!