Reputation: 11900
Consider I have an array-object which looks like this
const options = [{ label: "" }, { label: "123" }]
Now, I want to filter it and remove object which have label
value equal to ""
and then add order property equivalent to index to those object in an array having some value for label
I am able to do with combination of lodash filter and map but I was thinking if I could do it in a better way (probably using just filter?)
const options = _.filter(options, "label").map(
(option, position) => {
return {
...option,
order: position
}
}
)
Upvotes: 0
Views: 893
Reputation: 91
as i understand , you can use the pure js filter :
const options = [{
label: ""
}, {
label: "123"
}]
var index = 0;
const res = options.filter((e, i) => {
e = Object.assign(e,{});
if (e.label) {
e.order = index++;
return e;
}
})
console.log(res)
Edit: you can also use map and new array to call one function and remain your source pure:
const options = [{
label: ""
}, {
label: "123"
}]
var newArr = [];
options.map((e,r)=>{
if(e.label){
newArr.push({...e,order:newArr.length});
}
})
console.log(options)
console.log(newArr)
Upvotes: 0
Reputation: 412
Another pure JS solution could be:
const options = [{ label: "" }, { label: "123" }];
const modified = options.filter((el) => el.label.length).map((option, i) => ({ ...option, order: i }));
console.log(modified);
Upvotes: 0
Reputation: 50884
I personally think that what you have now is fine as its quite readable. One different idea could be to use _.flatMap()
instead, which will only require one iteration of your options
array. If the label is present in an object then you can return the modified object. If the label isn't present then you can return an empty array. As you're flattening into the resulting array for every value you return, the empty array won't be included in the resulting array.
const options = [{ label: "" }, { label: "123" }];
const res = _.flatMap(options, (o, order) => o.label ? {...o, order} : []);
console.log(res);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.min.js"></script>
Note: You can also use the vanilla version of .flatMap()
, so you don't need to use lodash unless you need good browser support or are using it for other code.
Upvotes: 2