根据javascript中的id删除对象内部数组中的对象

时间:2019-03-21 13:46:20

标签: javascript arrays object

正如标题所说,我正在尝试根据ID删除对象内部数组中的对象。请在下面查看我的对象:

{"satisfied":[],
"support":
[
    {"id":187,"question":"supot1"}
],
"agree":
[
    {"id":891,"question":"asdff"},
    {"id":394,"question":"Dos"},
    {"id":495,"question":"Tres"}
],
"yesno":[],
"multichoice":
[
    {"id":785,"question":"multi1",
    "choices":["item1","item2", "item3"]},
    {"id":986,"question":"multi2",
    "choices":["item4", "item5", "item6"]}
],
"oneofmany":[]
}

例如,我想删除{“ id”:891,“ question”:“ asdff”},我将如何处理?

3 个答案:

答案 0 :(得分:0)

要遍历所有这些子数组,可以遍历对象的值:

 for(const array of Object.values(input)) {

然后在该数组中搜索匹配的对象,并在必要时将其拼接:

  const toFind = 891;
  const index = array.findIndex(it => it.id === toFind);
  if(index !== -1) 
    array.splice(index, 1);
 }

答案 1 :(得分:0)

尝试一下

var obj = {
  "satisfied":[],
  "support":
  [
      {"id":187,"question":"supot1"}
  ],
  "agree":
   [
      {"id":891,"question":"asdff"},
      {"id":394,"question":"Dos"},
      {"id":495,"question":"Tres"}
   ],
   "yesno":[],
   "multichoice":
    [
       {"id":785,"question":"multi1","choices":["item1","item2", "item3"]},
       {"id":986,"question":"multi2","choices":["item4", "item5", "item6"]}
    ],
    "oneofmany":[]
}

let id= {"id":891,"question":"asdff"}.id; //need to remove 
Object.keys(obj).forEach(function(key) {
  var index = obj[key].map(x => {return x.id;}).indexOf(id);
  if (index > -1) {
    obj[key].splice(index, 1);
  }
});

console.log(obj);

答案 2 :(得分:0)

我用过lodash(_.remove),效果很好

  var origArray = questions_list[$itemType];
   _.remove(origArray, function(n){
          return n.id == $itemId;
  });