Wednesday, June 5, 2024
 Popular · Latest · Hot · Upcoming
111
rated 0 times [  115] [ 4]  / answers: 1 / hits: 31736  / 7 Years ago, mon, march 27, 2017, 12:00:00

I have a javascript object like the one below with several fields and arrays and arrays within arrays. I'm only interested only in non-junk fields and wanted to remove all the junk properties from the objects. How can I do that using lodash?



I can do that by using delete, but I don't want to do that because that list is huge and I don't want to keep changing my code to write a delete every time a new junk property is added to my object.



{
state: 'New York',
country: 'usa',
counties : [['washington','DC'],'Long Island',['New','Jersey']],
city : 'Manhattan',
zip: '43543545',
JunkOne : ['3453454','45345','45345'],
JunkTwo: '5454545',
JunkThree: {adc:'4545',vdfd:'45345'}
}

More From » lodash

 Answers
8

You can use lodash.pick() to create an object with only the requested keys. For example:



var city = {
state: 'New York',
country: 'usa',
counties : [['washington','DC'],'Long Island',['New','Jersey']],
city : 'Manhattan',
zip: '43543545',
JunkOne : ['3453454','45345','45345'],
JunkTwo: '5454545',
JunkThree: {adc:'4545',vdfd:'45345'}
}
var lodash = require('lodash');
city = lodash.pick(city, ['state', 'country', 'counties','city','zip']);


City now should have all the useful data, and none of the junk.


[#58365] Friday, March 24, 2017, 7 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
colby

Total Points: 311
Total Questions: 102
Total Answers: 102

Location: Taiwan
Member since Mon, Sep 6, 2021
3 Years ago
;