gpt4 book ai didi

javascript - 过滤掉同一键上的对象数组为空 ("")

转载 作者:行者123 更新时间:2023-11-30 20:07:44 24 4
gpt4 key购买 nike

我有一个需要过滤的对象数组。它看起来像这样:

        let array = [
{
"id": "",
"first_name": "Kary",
"last_name": "Thorndale",
"email": "kthorndale1@nifty.com",
"gender": "Female",
"ip_address": "172.152.36.109"
},
{
"id": "",
"first_name": "Westley",
"last_name": "Emmott",
"email": "wemmott2@cisco.com",
"gender": "Male",
"ip_address": "104.62.125.170"
},
{
"id": "",
"first_name": "Gavrielle",
"last_name": "Danihel",
"email": "gdanihel3@yandex.ru",
"gender": "Female",
"ip_address": "98.98.209.17"
}
];

我只有一个条件 - 如果所有对象中的键为空,则将其从所有对象中移除。

如果速度更快或有任何需要,我可以使用 jQuery 或 loDash。

数组中的对象不应超过 15-20 个,并且最多将有 15 个这样的数组需要通过过滤器。

最佳答案

您可以计算相同键的空值并映射没有所有空属性的新对象。

var array = [{ id: "", first_name: "Kary", last_name: "Thorndale", email: "kthorndale1@nifty.com", gender: "Female", ip_address: "172.152.36.109" }, { id: "", first_name: "Westley", last_name: "Emmott", email: "wemmott2@cisco.com", gender: "Male", ip_address: "104.62.125.170" }, { id: "", first_name: "Gavrielle", last_name: "Danihel", email: "gdanihel3@yandex.ru", gender: "Female", ip_address: "98.98.209.17" }],
keys = Array
.from(array.reduce((m, o) => {
Object.entries(o).forEach(([k, v]) => m.set(k, (m.get(k) || 0) + +!!v));
return m;
}, new Map))
.filter(({ 1: v }) => v)
.map(([k]) => k),
result = array.map(o => Object.assign(...keys.map(k => ({ [k]: o[k] }))));

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

稍微好一点的版本带有 Set

var array = [{ id: "", first_name: "Kary", last_name: "Thorndale", email: "kthorndale1@nifty.com", gender: "Female", ip_address: "172.152.36.109" }, { id: "", first_name: "Westley", last_name: "Emmott", email: "wemmott2@cisco.com", gender: "Male", ip_address: "104.62.125.170" }, { id: "", first_name: "Gavrielle", last_name: "Danihel", email: "gdanihel3@yandex.ru", gender: "Female", ip_address: "98.98.209.17" }],
keys = Array.from(
array.reduce(
(s, o) => Object.entries(o).reduce((t, [k, v]) => v ? t.add(k) : t, s),
new Set
)
),
result = array.map(o => Object.assign(...keys.map(k => ({ [k]: o[k] }))));

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

关于javascript - 过滤掉同一键上的对象数组为空 (""),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52704912/

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