-1

I have an object:

var obj = { a: 'test1', b: 'test2', c: 'test3', d: 'test4', e: 'test5', f: 'test6', g: 'test7', h: 'test8' }

I want to get result:

res = { a: 'test1', c: 'test3', d: 'test4' }

What is the fastest way to do it?

KitKit
  • 6,971
  • 11
  • 44
  • 74

2 Answers2

6

Directly access the fields:

res = {a: obj.a, c: obj.c, d: obj.d};
T.J. Crowder
  • 959,406
  • 173
  • 1,780
  • 1,769
1

i think you want to delete key-value pair from the object so for that here's the solution

delete obj[b];

delete obj[e];

or you can use lodash pick

var _ = require('lodash')
_.pick( obj, [a, c, d] )

or create a new Object

var final = {a: obj.a, c: obj.c, d: obj.d}
Atishay Jain
  • 1,345
  • 11
  • 21
  • You might want to test that. Particularly test accessing other properties on `obj` after you do it. :-) `delete` has a significant unfortunate affect on the performance of objects you apply it to. – T.J. Crowder Oct 19 '18 at 08:04
  • yeah, but i've seen a lot of cases where one need to change the current variable only instead of creating a new one. That's why i've multiple methods. Anyway thanks for pointing that out. :) – Atishay Jain Oct 19 '18 at 08:09
  • Well, you didn't [when I posted that comment](https://stackoverflow.com/revisions/52888187/1). And `_.pick` is certainly not going to be the "fastest" way (not even remotely). – T.J. Crowder Oct 19 '18 at 08:18