remove object inside array inside an object based on id in javascript

问题: as the title say i'm trying to remove an object inside an array inside an object based on an id. Please see my object below: {"satisfied":[], "support": [ {"id":187,"...

问题:

as the title say i'm trying to remove an object inside an array inside an object based on an id. Please see my object below:

{"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":[]
}

For example, i'd like to delete {"id":891,"question":"asdff"}, how will i go about this?


回答1:

To go over all those subarrays you could iterate over the values of the object:

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

Then in that array, search for an object that matches and splice it out if necessary:

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

回答2:

Try this

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);


回答3:

i used lodash (_.remove), works fine

  var origArray = questions_list[$itemType];
   _.remove(origArray, function(n){
          return n.id == $itemId;
  });
  • 发表于 2019-03-22 18:02
  • 阅读 ( 158 )
  • 分类:sof

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除