Skip to content Skip to sidebar Skip to footer

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,'question':

Solution 1:

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

for(constarray 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);
 }

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

Solution 3:

i used lodash (_.remove), works fine

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

Post a Comment for "Remove Object Inside Array Inside An Object Based On Id In Javascript"