My data structure (this.terms) looks like this:
{
name: 'First Category',
posts: [
{
name: 'Jim James',
tags: [
'nice', 'friendly'
]
},
{
name: 'Bob Ross',
tags: [
'nice', 'talkative'
]
}
]
},
{
name: 'Second Category',
posts: [
{
name: 'Snake Pliskin',
tags: [
'mean', 'hungry'
]
},
{
name: 'Hugo Weaving',
tags: [
'mean', 'angry'
]
}
]
}
I have a method that filters this.terms by tags and outputs the computed results.
computed: {
filteredTerms: function() {
let self = this;
let terms = this.terms;
if(this.search.tags) {
return terms.filter((term) => {
let updated_term = {};
updated_term = term;
let updated_posts = term.posts.filter((post) => {
if (post.tags.includes(self.search.tags)) {
return post;
}
});
if (updated_posts.length) {
updated_term.posts = updated_posts;
return updated_term;
}
});
} else {
return this.terms;
}
}
},
The filteredTerms() method returns categories with only matching posts. For example, a search for "angry" returns just "Second Category" with only "Hugo Weaving" listed.
The issue is that running the computed function changes Second Category in this.terms instead of in the copy of it (terms) within the function only. The line causing this is updated_term.posts = updated_posts. It seems to also alter this.terms. Resetting the entire data object every time isn't ideal as it would require loading everything again. I need this.terms to remain untouched so I can revert back to it after clearing search criteria.
I've tried different approaches like using lodash versions of filter and includes, as well as using loops and push(), but the issue persists. Any insights would be appreciated. Thank you for your help.