\$\begingroup\$
\$\endgroup\$
I got this data structure and I am checking to see which properties are true, then I am adding the key
for all the properties that are true to that object on a new property called combined
const data = [
{
keyword: 'banana',
yellow: true,
sweet: true
},
{
keyword: 'pineapple',
yellow: true,
sweet: false
},
{
keyword: 'apple',
yellow: false,
sweet: false
},
]
const combined = [...data].reduce((acc, { keyword, ...rest}) => {
const res = Object.entries(rest).reduce((total, [key, value]) => {
if (value === true) total.push(key)
return total
}, [])
acc.push(res)
return acc
}, []).map(entry => ({ combined: entry.join(' ') }))
const output = data.map((entry, index) => ({
...entry,
...combined[index]
}))
console.log(output)
.as-console-wrapper { max-height: 100% !important; top: 0; }
It seems pretty straight forward but somehow this feels a bit convoluted
Álvaro
2 Answers 2
\$\begingroup\$
\$\endgroup\$
1
From a short review;
- Your own answer does read better
map
is the right approach- I would go for
filter
instead ofreduce
(you only want 'true' values that are not keyword) - I probably would have named
total
->keys
- I prefer
<verb><object>
socombined
->addGroups
- If you dont use a falsy comparison, then you dont need to check for
'keyword'
const data = [
{keyword: 'banana', yellow: true, sweet: true},
{keyword: 'pineapple', yellow: true, sweet: false},
{keyword: 'apple', yellow: false, sweet: false},
];
function addGroup(o){
return {
...o,
group: Object.keys(o).filter(key => o[key] === true).join(' ')
};
}
function addGroups(list){
return list.map(o => addGroup(o));
}
console.log(addGroups(data))
.as-console-wrapper { max-height: 100% !important; top: 0; }
answered Apr 12, 2021 at 14:15
-
1\$\begingroup\$ Thank you for your answer, it works great. Any reason why you would no do something simpler like this:
const addGroups = (arr) => arr.map(obj => ({ ...obj, group: Object.keys(obj).filter(key => obj[key] === true).join(' ') }))
\$\endgroup\$Álvaro– Álvaro2021年04月13日 11:25:47 +00:00Commented Apr 13, 2021 at 11:25
\$\begingroup\$
\$\endgroup\$
I have improved it with this:
const data = [
{
keyword: 'banana',
yellow: true,
sweet: true
},
{
keyword: 'pineapple',
yellow: true,
sweet: false
},
{
keyword: 'apple',
yellow: false,
sweet: false
},
]
const combined = [...data].map((entry) => {
const group = Object.entries(entry).reduce((total, [key, value]) => {
if (value && key !== 'keyword') total.push(key)
return total
}, []).join(' ')
return {
...entry,
group
}
})
console.log(combined)
.as-console-wrapper { max-height: 100% !important; top: 0; }
Is this a better approach?
Explore related questions
See similar questions with these tags.
lang-js