2

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?

3
  • Could the object occur in any of the categories? Commented Mar 21, 2019 at 13:48
  • yup, i'm adding objects based on category, if they are satisfied type, support type, agree type, yesno type...etc Commented Mar 21, 2019 at 13:51
  • i've searched a lot, but examples only offer removal of simple arrays Commented Mar 21, 2019 at 13:52

3 Answers 3

0

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);
 }
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

0

i used lodash (_.remove), works fine

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.