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

时间:2018-04-24 16:56:16

标签: javascript associative-array

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

我试过过滤器和拼接,但两者都只适用于数组而不是数组。

4 个答案:

答案 0 :(得分:2)

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

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

答案 1 :(得分:1)

您可能需要地图。我认为Map确实比你实际需要的更好。

答案 2 :(得分:1)

这是地图的完美用例:

  class Multimap extends Map {
    get(key) {
      return super.get(key) || [];
    }

    addTo(key, value) {
      if(this.has(key)) {
         this.get(key).push(value);
       } else {
         this.set(key, [value]);
       }
    }

    removeFrom(key, value) {
      this.set(key, this.get(key).filter(el => el !== value));
    }
}

这可以用作:

 const cm = new Multimap([
  ["a", ["a", "b", "c"]]
 ]);

 cm.removeFrom("a", "b");
 cm.get("a").includes("b") // false

答案 3 :(得分:0)

我像这样在数组上使用了.filter

// Remove emptys
modeSummary = modeSummary.filter(ms => ms);