问题:
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;
});