JavaScript - 删除对象数组中的对象属性

JavaScript - delete object properties in array of objects

是否有比以下示例更好/更短的方法来从对象数组中的对象中删除属性。我可以使用 vanilla JS 或 lodash。

示例函数:

  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;
  } 

我可以想到两个办法

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]);
    }
}

或者 - 假设 newLay 是错字

function stripObjProps(arr) {
    return arr.map(item => {
        let {
            isBounded,
            isDraggable,
            isResizable,
            maxH,
            maxW,
            minH,
            minW,
            resizeHandles,
            moved,
            static,
            ...ret
        } = item;
        return ret;
    });
}

注意:在第二个示例中不需要 _.clone,因为您没有进行深度克隆,映射 returns 具有新对象的新数组 (...ret)

但是,我不使用 lodash,所以可能有更好的方法 library

您可以使用 Lodash 中的 omit 来排除属性:

function stripObjProps(arr) {
    return arr.map(item => _.omit(item, ['isBounded', 'isDraggable', 'isResizable', 'maxH', 'maxW', 'minH', 'minW', 'resizeHandles', 'moved', 'static']));
}

const newArray = stripObjProps(originalArray)

此外,您可以使用 pick 而不是 omit。在 pick 的情况下,您仅指定要保留的属性。

使用 filter 和对象 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}