首页 > 解决方案 > 从对象数组中的每个对象中删除对象

问题描述

我想通过删除表不使用的所有嵌套对象来提高大型数据集的表性能。我不想命名键,因为它们会因数据集而异。这需要是一个可重用的辅助函数,它根据typeof而不是键删除对象。

示例数据:

const data = [
  { test: 1, notes: [] },
  { test: 2, notes: [] },
  { test: 3, notes: [] }
];

预期结果

[
  { test: 1 },
  { test: 2 },
  { test: 3 }
];

我试过的:

  const simpleRows = (arr) => {
    var rows = arr.map(({ notes, ...keepAttrs }) => keepAttrs);
    return rows;
  };

  const rows = simpleRows(data) // This works but I have hardcoded the key 'notes' which I don't want

什么是从大型数据集中对象数组(数组中约 10000 个对象)中的每个对象中删除所有对象的最有效方法,而无需对密钥进行硬编码,也无需外部库?

谢谢

标签: javascript

解决方案


您可以过滤每个对象的条目并从过滤的条目中创建一个新对象:

const data = [
  { test: 1, notes: [] },
  { test: 2, notes: [] },
  { test: 3, notes: [] }
]
const result = data.map(obj => Object.fromEntries(Object.entries(obj).filter(([_, v]) => !Array.isArray(v))))
console.log(result)


推荐阅读