Given an array:
var arrOfObj = [{
name: 'eve',
col1 : 1,
col2 : 0,
col3 : 1
}, {
name: 'john',
col1 : 1,
col2 : 1,
col3 : 0
}, {
name: 'jane',
col1 : 0,
col2 : 1,
col3 : 1
}];
I need a field inside the array that has a string of the names of columns col1, col2, col3 if they are 1. Sample outcome is:
var arrOfObj = [{
name: 'eve',
col1 : 1,
col2 : 0,
col3 : 1,
account : "col1,col3"
} //etc
}]
I can currently achieve this with
var result = arrOfObj.map(function(o) {
o.account = ""
if (o.col1 > 0) {o.account = o.account + "col1,"} ;
if (o.col2 > 0) {o.account= o.account + "col2,"} ;
if (o.col3 > 0) {o.account= o.account + "col3,"} ;
o.account = o.account.slice(0, -1);
return o;
})
console.log(result)
but as a novice to JS this feels inefficient. My actual array has a dozen such columns being evaluated.
Edit: finished product with assistance from the accepted answer:
var bool_cols = ["col1","col2","col3"]
data.forEach(x => {
x.services = Object.keys(x).filter (y => bool_cols.includes(x) && x[y] == 1).join (',');
})
I like how I can expand the filter criteria indefinitely!