简体   繁体   中英

If I use lodash's union to merge objects based on a set of boolean settings, how would one write it elegantly?

I've encountered a programming problem I've never encountered before. I am merging object data based on user defined settings. Does anyone know how to program this without a bunch of (inelegant) nested if/else statements? _union takes an array.

import _ from 'lodash';

// Real data structure is more complex, but is an array that contains objects like so
let dataset1 = [{ "name": "John" }, { "name": "Paul" }];
let dataset2 = [{ "name": "Laura" }, { "name": "Eline" }];
let dataset3 = [{ "name": "Boris" }, { "name": "Tanya" }];

// These are use configurable settings, real dataset is user defined
let dataSetActive1 = true;
let dataSetActive2 = true;
let dataSetActive3 = false;

// this is the dataset I need in this case of true, true, false - but how to  
// write this elegantly when the truth/false changes?
let dataset = _.union(dataset1, dataset2); 

My favorite way to do that would be:

 let dataset1 = [{ "name": "John" }, { "name": "Paul" }]; let dataset2 = [{ "name": "Laura" }, { "name": "Eline" }]; let dataset3 = [{ "name": "Boris" }, { "name": "Tanya" }]; let dataSetActive1 = true; let dataSetActive2 = true; let dataSetActive3 = false; let dataset = _.union( dataSetActive1 && dataset1, dataSetActive2 && dataset2, dataSetActive3 && dataset3 ) .filter(Boolean); console.log(dataset)
 <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.min.js"></script>

filter(Boolean) will filter out all the falsy values from the array, which will be when your setting is false.

Use a ternary to return an empty array for each Active variable/const which is false .

Since the items in your array are objects _.union() , which uses the SameValueZero algorithm ,would never find and remove duplicates. Because if Object A, and Object B are not the same object, they are not equal. Use _.unionBy() with the name as the iteratee used as the uniqueness criterion.

 const dataset1 = [{ "name": "John" }, { "name": "Paul" }]; const dataset2 = [{ "name": "Laura" }, { "name": "Eline" }]; const dataset3 = [{ "name": "Boris" }, { "name": "Tanya" }]; const dataSetActive1 = true; const dataSetActive2 = true; const dataSetActive3 = false; const result = _.unionBy( dataSetActive1 ? dataset1 : [], dataSetActive2 ? dataset2 : [], dataSetActive3 ? dataset3 : [], 'name' ); console.log(result)
 <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.min.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