gpt4 book ai didi

javascript 从 assoc 数组中删除(空)数组

转载 作者:行者123 更新时间:2023-11-28 14:35:15 25 4
gpt4 key购买 nike

我有一个 assoc js 数组,我想从中删除一个元素。我的解决方案有效,但不太好,有更好的解决方案吗?

// i got this assoc array
var cm = [];
cm["a"] = ["a"];
cm["b"] = ["c"];
cm["s"] = ["a", "b", "c"];
cm["x"] = [];
console.log(cm);

var searchKey = "s";
var p = ["a","c","d", "b"]; // to remove from searchKey array

// remove elements (works fine)
cm[searchKey] = cm[searchKey].filter(value => (p.includes(value) === false));
console.log(cm); // now cm[searchKey] is an empty array

// if the array at index 'searchKey' is empty remove it from assoc array
var newarray = [];
if (cm[searchKey].length===0)
{
for(key in cm)
{
if (key!=searchKey) newarray[key] = cm[key];
}
}
cm = newarray;
console.log(cm);

我尝试使用过滤器和拼接,但两者都仅适用于数组而不是关联数组。

最佳答案

你有一个对象,所以你可以这样做:

if (cm[searchKey].length===0)
{
delete cm[searchKey]
}

关于javascript 从 assoc 数组中删除(空)数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50007162/

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