gpt4 book ai didi

合并对象后 Javascript 不需要的 "empty"属性

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

我想根据一个属性合并对象,我想使用这个属性作为合并数组的键。这是我的代码:

 let mergedProfiles = [];
for (let set of profiles) {
if (Object.keys(mergedProfiles).indexOf(String(set.profile_id)) >= 0) { // if profile id exists
mergedProfiles[set.profile_id].push(set);
} else {
mergedProfiles[set.profile_id] = [];
mergedProfiles[set.profile_id].push(set);
}
}

配置文件对象示例:{user_id: 17, name: "test", country: "US", bid: 0.02, profile_id: "1", user_id: 12}

合并工作正常,但出于某种原因我无法理解我总是以 empty 作为我在 mergedProfiles 中的第一个属性,知道缺少什么吗?

最佳答案

您可以使用对象而不是数组,因为您得到的是一个没有使用索引的稀疏数组。

var profiles = [{ user_id: 17, name: "test", country: "US", bid: 0.02, profile_id: "1", user_id: 12 }],
mergedProfiles = {},
s;

for (s of profiles) {
if (!mergedProfiles[s.profile_id]) {
mergedProfiles[s.profile_id] = [];
}
mergedProfiles[s.profile_id].push(s);
}

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

关于合并对象后 Javascript 不需要的 "empty"属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48619926/

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