3
let obj = { a: 1, b:2, c:3}

I can do

let {a,b,c}  = obj

but i want an object with just 'a' and 'b' as key and same value as in obj

do i have a syntax for that one

it is basically filtering out the keys but do we have some succint syntax for this one because I constantly do

let test = {
  a: obj.a,
  b: obj.b
}
ashish singh
  • 5,232
  • 1
  • 9
  • 27

3 Answers3

1

how about let n = ({a,b} = obj) && {a,b}?

Koushik Chatterjee
  • 3,738
  • 3
  • 15
  • 29
  • How about not using global variables? – Bergi Aug 20 '17 at 10:38
  • @Bergi so the typical answer to this basically doing the same thin but because that is happening inside a function those variables dies inside function scope, (the parameters of the functions), but the OP just wanted to avoid calling another function to filter it – Koushik Chatterjee Aug 21 '17 at 12:13
  • You can do it without a function as well - there are many ways - but you have to declare `a` and `b` to *some* scope. IIFEs are just quite concise. – Bergi Aug 21 '17 at 13:19
0

Using object destructuring, Hope this helps

var obj = {"a":1, "b":2, "c":3}
var test = (({a, b}) => ({a, b}))(obj);

console.log(test);
Suresh Prajapati
  • 2,990
  • 2
  • 19
  • 34
  • thanks for the answer .i know it can be done... i wanted to know if there is a syntax . – ashish singh Aug 20 '17 at 07:47
  • If you are looking for exact syntax, I don't think so It's available, but would definitely love to know if a syntax exists in js. Otherwise, you will need to use better techniques (or one-liner) or your own function to do that which should be better than `let test = { a: obj.a, b: obj.b }` – Suresh Prajapati Aug 20 '17 at 08:00
0

The following does this:

let result = {}
Object.keys(obj)
    .filter(e=>![LIST WITH KEYS TO FILTER].includes(e))
    .forEach(e=> result[e]= obj[e])

It gets all keys from obj, filters out some keys and pushes the values of the leftover keys to the result object.