javascript - 从对象数组中的每个对象中删除对象
问题描述
我想通过删除表不使用的所有嵌套对象来提高大型数据集的表性能。我不想命名键,因为它们会因数据集而异。这需要是一个可重用的辅助函数,它根据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 个对象)中的每个对象中删除所有对象的最有效方法,而无需对密钥进行硬编码,也无需外部库?
谢谢
解决方案
您可以过滤每个对象的条目并从过滤的条目中创建一个新对象:
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)
推荐阅读
- java - 如何获取从 jList 中选择的对象
- html - 为什么两个引导切换按钮会导致问题?
- python - 我有两个数据框。我想根据条件将一个数据帧的值替换为另一个数据帧的标头值
- jquery - 如何在 Kendo UI Grid 的 onDataBound 事件中检查现有行值是否更改?
- excel - 从文本中清除数字并粘贴为外部工作簿中的值
- javascript - 如何复制多个表格单元格数据,然后将数据正确粘贴到目标位置?
- android - 多个dex文件定义 Lcom/google/protobuf/AbstractMessageLite$Builder$LimitedInputStream;
- magento - Magento 2.3 不发送任何电子邮件
- excel - 在子文件夹中打开文件
- gtk - gtk(mm) 3 锚定在文本视图中的文本视图无法将光标移入