Is there a better / shorter method to delete properties from objects in an array of objects than the below example. I can use vanilla JS or lodash.
Exmaple function:
function stripObjProps(arr) {
let newArr = _.clone(arr);
for (let i = 0; i < arr.length; i = 1) {
delete newArr[i].isBounded;
delete newArr[i].isDraggable;
delete newArr[i].isResizable;
delete newArr[i].maxH;
delete newArr[i].maxW;
delete newArr[i].minH;
delete newArr[i].minW;
delete newArr[i].resizeHandles;
delete newArr[i].moved;
delete newArr[i].static;
}
return newArr;
}
CodePudding user response:
I can think of two ways
function stripObjProps(arr) {
let newArr = _.clone(arr);
for (let i = 0; i < newLay.length; i = 1) {
[
"isBounded",
"isDraggable",
"isResizable",
"maxH",
"maxW",
"minH",
"minW",
"resizeHandles",
"moved",
"static"
].forEach(k => delete newArr[i][k]);
}
}
or - assuming newLay
is a typo
function stripObjProps(arr) {
return arr.map(item => {
let {
isBounded,
isDraggable,
isResizable,
maxH,
maxW,
minH,
minW,
resizeHandles,
moved,
static,
...ret
} = item;
return ret;
});
}
NOTE: no need for _.clone
in this second example, since you aren't doing a deep clone, map returns a new array with a new object (...ret
)
However, I don't use lodash, so there may be an even better way with that library
CodePudding user response:
You can use omit
from Lodash to exclude properties:
function stripObjProps(arr) {
return arr.map(item => _.omit(item, ['isBounded', 'isDraggable', 'isResizable', 'maxH', 'maxW', 'minH', 'minW', 'resizeHandles', 'moved', 'static']));
}
const newArray = stripObjProps(originalArray)
Additionally, you can use pick
instead of omit
. In case of pick
you specify only the properties which you want to keep.