JavaScript / Underscore基于嵌套数组中的对象属性删除数组

时间:2017-03-25 15:26:11

标签: javascript arrays underscore.js

我的数组看起来像这样

var array = [
  {
    "name" : "abc",
    "items" : [
       {
         "name": "def"
         "url" : "https://"
       },
       {
         "name": "jkl"
         "url" : "http://"
       }
    ]
  },
  {
   "name" : "ghi",
   "items" : [
      {
         "name": "jkl"
         "url" : "http://"
      }
    ]
  }
]

我如何删除对象' jkl'在里面' abc'最好使用下划线

1 个答案:

答案 0 :(得分:1)



var array = [
  {
    "name" : "abc",
    "items" : [
       {
         "name": "def",
         "url" : "https://"
       },
       {
         "name": "jkl",
         "url" : "http://"
       }
    ]
  },
  {
   "name" : "ghi",
   "items" : [
      {
         "name": "jkl",
         "url" : "http://"
      }
    ]
  }
]

console.log("Array before = ",array);

array = array.map( elem => {
   if(elem.name !== "abc") return elem;
   elem.items = elem.items.filter(item => item.name !== "jkl" );
   return elem;
})

console.log("Array after = ",array);