[英]javascript remove (empty) array from assoc 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);
我嘗試過過濾器和拼接,但兩者都只適用於數組而不是關聯數組。
你有一個對象,所以你可以這樣做:
if (cm[searchKey].length===0)
{
delete cm[searchKey]
}
你可能需要地圖。 我認為 Map 做得比您實際要求的更好。
這是 Map 的完美用例:
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
我像這樣在數組上使用了.filter
// Remove emptys
modeSummary = modeSummary.filter(ms => ms);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.