http://jsfiddle.net/0444046b/12/
I have a complex Array of objects, each object has it's own tag Array.
I also have just an object which should match one of the objects in the tag Array, and if so remove that tag.
Got some help here, however my example there was too simple, so far no luck with this below.
Basically I have the object tag and I need to remove it from the tags Array inside of tagsArray.
var tagsArray = [{
name: "group1",
tags: [
{
name: "1",
tag_id: "1234"
},
{
name: "2",
tag_id: "5678"
},
{
name: "3",
tag_id: "9012"
}
]
},
{
name: "group2",
tags: []
}
];
console.log(tagsArray[0]);
// Need to find this inside of tags inside of tagsArray and remove it:
var tag = {
name: "3",
tag_id: "9012"
}
var temp_array = [];
temp_array.push(tag);
var map = {};
tagsArray.forEach(function(obj, index) {
map[obj.tag_id] = index;
});
console.log(map);
temp_array.forEach(function(obj) {
if ( obj.tag_id ) {
tagsArray.splice(tagsArray[map[obj.tag_id]]);
console.log(tagsArray);
}
});
2 Answers 2
You can loop through each item in tagsArray and then filter our matching elements in the inner tags property.
var tagsArray = [{
name: "group1",
tags: [{
name: "1",
tag_id: "1234"
}, {
name: "2",
tag_id: "5678"
}, {
name: "3",
tag_id: "9012"
}]
}, {
name: "group2",
tags: []
}];
// Need to find this inside of tags inside of tagsArray and remove it:
var removeTag = {
name: "3",
tag_id: "9012"
}
var message = 'Before:<br>' + JSON.stringify(tagsArray) + '<br><br>';
tagsArray.forEach(function(element) {
element.tags = element.tags.filter(function(tag) {
return tag.name != removeTag.name && tag.tag_id != removeTag.tag_id;
})
});
message += 'After:<br>' + JSON.stringify(tagsArray);
document.body.innerHTML = message
1 Comment
The solution of Daniel Imms is totally fine, but this one also can solve your problem, and it is a bit faster.
var tagsArray = [{
name: "group1",
tags: [{
name: "1",
tag_id: "1234"
}, {
name: "2",
tag_id: "5678"
}, {
name: "3",
tag_id: "9012"
}]
}, {
name: "group2",
tags: [{
name: "4",
tag_id: "1012"
}]
}];
var removedTag = {
name: "4",
tag_id: "1012"
};
var message = 'Before:</br>' + JSON.stringify(tagsArray) + '</br></br>';
tagsArray.forEach(function(obj, i) {
obj.tags.forEach(function(tag, j) {
if (tag.tag_id === removedTag.tag_id && tag.name === removedTag.name) {
obj.tags.splice(j, 1);
return;
}
});
});
message += 'After:</br>' + JSON.stringify(tagsArray);
document.body.innerHTML = message
I tested with jsPerf and here is the link and here is the result. enter image description here
1 Comment
filter was for some reason removing all my tag objects.