gpt4 book ai didi

javascript - 如何减少数组中哈希的键?

转载 作者:行者123 更新时间:2023-12-04 00:06:45 25 4
gpt4 key购买 nike

例如:(我假设像 JSON 数据)

const arr = [
{foo: 1, bar: 2, hoge: 3, fuga: 4},
{foo: 1, bar: 2, hoge: 3, fuga: 4},
{foo: 1, bar: 2, hoge: 3, fuga: 4},
{foo: 1, bar: 2, hoge: 3, fuga: 4},...
]

我不需要 barfuga 键,所以我想像这样从这个数组中提取

[
{foo: 1, hoge: 3},
{foo: 1, hoge: 3},
{foo: 1, hoge: 3},
{foo: 1, hoge: 3},...
]

我怎样才能以简单的方式做到这一点?

最佳答案

如果你不需要一个单独的数组,你可以简单地通过迭代数组来删除那些属性:

const arr = [
{foo: 1, bar: 2, hoge: 3, fuga: 4},
{foo: 1, bar: 2, hoge: 3, fuga: 4},
{foo: 1, bar: 2, hoge: 3, fuga: 4},
{foo: 1, bar: 2, hoge: 3, fuga: 4}
];

arr.forEach(function(t) {
delete t.bar;
delete t.fuga;
});

console.log(arr);

作为 delete 的替代方法,您也可以将这些属性设置为 undefinedIt is known to be somewhat faster , 但请注意 the two are not equivalent .

const arr = [
{foo: 1, bar: 2, hoge: 3, fuga: 4},
{foo: 1, bar: 2, hoge: 3, fuga: 4},
{foo: 1, bar: 2, hoge: 3, fuga: 4},
{foo: 1, bar: 2, hoge: 3, fuga: 4}
];

arr.forEach(function(t) {
t.bar = undefined;
t.fuga = undefined;
});

console.log(arr);

关于javascript - 如何减少数组中哈希的键?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48982560/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com