'JavaScript - delete object properties in array of objects
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;
}
Solution 1:[1]
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
Solution 2:[2]
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.
Solution 3:[3]
Another way to remove properties with filter and Object entries / fromEntries.
const data = [
{ a: 1, b: 2, c: 3, d: 4, e: 5 },
{ a: 1, b: 2, c: 3, d: 4, e: 5 },
{ a: 1, b: 2, c: 3, d: 4, e: 5 },
];
const excludeKeys = ['b', 'c', 'd'];
const exclude = (obj) =>
Object.fromEntries(
Object.entries(obj)
.filter(([key]) => !excludeKeys.includes(key)));
const result = data.map(exclude);
console.log(result);
.as-console-wrapper {max-height: 100% !important; top: 0}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Ervin Szilagyi |
| Solution 3 |
