I have a hierarchical javascript object, which I need to filter out some of its elements. I wonder if there is an easy way to do this.
For example I have an object actions
as below. I want to filter out those that have an default
property which is set to true
.
let actions={
sql: [
{
content: 'aaa',
default: true
},
{
stmt: 'bbb'
},
{
stmt: 'ccc',
default: true
}],
email: [
{
content: 'xxx',
default: true
}]
}
So eventually I want to have something like:
let filteredActions={
sql: [
{
stmt: 'bbb'
}
],
email: []
}
This how I try to solve my problem, but seems it does not work.
getNonDefaultActions = actions =>
map(actions, (actionListByType, key) => {
actionListByType.filter(action => !(action.defaultFlag === true))
});
It seems nothing has been filtered. Any solution is welcome. Additionally, if lodash provides something handy for this type of problem that would be great
You can use lodash's _.mapValue()
with _.reject()
:
const actions = {"sql":[{"content":"aaa","default":true},{"stmt":"bbb"},{"stmt":"ccc","default":true}],"email":[{"content":"xxx","default":true}]}
const result = _.mapValues(actions, arr => _.reject(arr, 'default'))
console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>