听听那晚风
2021-01-20 17:58
采纳率: 83.3%
浏览 151

将对象数组a中不包含数组b里的元素的项去除

var a = [
        { name: "aa", children: [{ name: "aa1" }, { name: "aa2" }] },
        { name: "bb", children: [{ name: "bb1" }, { name: "bb2" }] },
        { name: "cc", children: [{ name: "cc1" }, { name: "cc2" }] },
        { name: "dd", children: [{ name: "dd1" }, { name: "dd2" }] },
        { name: "ee", children: [{ name: "ee1" }, { name: "ee2" }] },
      ];
var b = ["aa1","aa2","cc1", "bb2","dd1" ];
//目标对象
var mune = [
        { name: "aa", children: [{ name: "aa1" },{ name: "aa2" }] },
        { name: "bb", children: [{ name: "bb2" }] },
        { name: "cc", children: [{ name: "cc1" }] },
        { name: "dd", children: [{ name: "dd1" }] },
      ];
  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • 蔣伟平 2021-01-20 21:10
    已采纳

    var a = [

            { name: "aa", children: [{ name: "aa1" }, { name: "aa2" }] },

            { name: "bb", children: [{ name: "bb1" }, { name: "bb2" }] },

            { name: "cc", children: [{ name: "cc1" }, { name: "cc2" }] },

            { name: "dd", children: [{ name: "dd1" }, { name: "dd2" }] },

            { name: "ee", children: [{ name: "ee1" }, { name: "ee2" }] },

          ];

    var b = ["aa1","aa2","cc1", "bb2","dd1" ];

     

    for(var i=0;i<a.length;i++){

      for(var j=0;j<a[i].children.length;j++){

        if(b.indexOf(a[i].children[j].name)==-1){

          a[i].children.splice(j,1);

          j--;

        }

      }

      if(a[i].children.length==0){

        a.splice(i,1);

        i--;

      }

    }

    点赞 评论
  • 听听那晚风 2021-01-21 10:12

    大佬牛逼,我弄的是新建一个数组,把包含的添加到新数组里,但是没你这个好

    var a = [
            { name: "aa", children: [{ name: "aa1" }, { name: "aa2" }] },
            { name: "bb", children: [{ name: "bb1" }, { name: "bb2" }] },
            { name: "cc", children: [{ name: "cc1" }, { name: "cc2" }] },
            { name: "dd", children: [{ name: "dd1" }, { name: "dd2" }] },
            { name: "ee", children: [{ name: "ee1" }, { name: "ee2" }] },
          ];
    var b = ["aa1","aa2","cc1", "bb2","dd1" ];
    
    let mm = [];
          a.forEach((v) => {
            let cc = [];
            for (let c = 0; c < v.children.length; c++) {
              let cv = v.children[c].name;
              let f = b.find((s) => s == cv);
              if (f) cc.push({ name: f });
            }
            v.children = cc;
            if (cc.length > 0) mm.push(v);
          });
          console.log(mm);
    
    点赞 评论