Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove all elements from object except specified key?

I have an object:

"languages": {
    "en":["au", "uk"],
    "de":["de"],
    ....
 }

How can I remove everything but a specified key, so if I specify 'en' I just want an object that contains "en":["au", "uk"]

like image 549
panthro Avatar asked Apr 12 '16 17:04

panthro


1 Answers

General solution for the original question of 'how do I remove all keys except specified keys' (refined from Rajaprabhu's answer):

validKeys = [ 'a', 'b', 'c' ];
userInput = { "a":1, "b":2, "c":3, "d":4, "e":5 }

Object.keys(userInput).forEach((key) => validKeys.includes(key) || delete userInput[key]);
like image 66
Dave Avatar answered Sep 26 '22 23:09

Dave