简体   繁体   中英

Lodash create new array from selected keys

My prop data is outputed as:

const { profile } = this.props;
console.log("help", profile);

{notes: "", name: "John", gender: "M", dob: "", age: "33", nationality: "British", notes2: "no notes", notes3: "no notes"}

I want to be able to pull out the notes and end up with something like this:

{notes: "", notes2: "no notes", notes3: "no notes"}

I need to keep "profile" as its own prop so would need to create a const to store this output.

I tried something like this:

const oldArray = _.map(_.toPairs(profile), d => _.fromPairs([d]));
const newArray = _.map(oldArray => [{notes: notes}, {notes: notes2}, {notes: notes3}]);

The reason I want to do this is to then run a check to see if all notes are empty, but cant do this whilst they sit in the array with lots of different keys.

If you have an object you could use _.pick method and return a new object with specific properties.

 const obj = {notes: "", name: "John", gender: "M", dob: "", age: "33", nationality: "British", notes2: "no notes", notes3: "no notes"} const notes = _.pick(obj, ['notes', 'notes2', 'notes3']); console.log(notes) 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.10/lodash.js"></script> 

You can loop through the keys of that object and check if the key has notes as a substring. If yes then add that key-value to a new object. Using this you do not need to worry about keys like notes1 , notes2 , notes3 , ... and so on. You can simply check for the substring notes :

 var obj = {notes: "", name: "John", gender: "M", dob: "", age: "33", nationality: "British", Notes2: "no notes", notes3: "no notes"}; var res = {}; Object.keys(obj).forEach((key) => { if(key.toLowerCase().indexOf('notes') !== -1){ res[key] = obj[key]; } }); console.log(res); 

You can use plain js instead of lodash:

const { profile } = this.props;
const { notes, notes2, notes3 } = profile;
const newObject  = { notes, notes2, notes3 };

Then you can check the values:

const hasValues = Object.values(newObject).filter(v => !!v).length > 0;

Use _.pickBy() with String.startsWith() (or lodash's equivalent ) to find all the keys that start with the word notes :

 const props = {notes: "", name: "John", gender: "M", dob: "", age: "33", nationality: "British", notes2: "no notes", notes3: "no notes"}; const notes = _.pickBy(props, (v, k) => k.startsWith('notes')); console.log(notes) 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.10/lodash.js"></script> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM