我有一个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);


我尝试使用filter和splice,但是两者都只能在数组上使用而不能在assoc数组上使用。

最佳答案

您有一个对象,因此您可以执行以下操作:

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

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

10-11 20:29