Reputation: 372
I have a filter method (itemsWithFilter) to filter my items object and write the results in itemsResult
this works for the first time but it seems that my function autmatically updated the items object too. Even so I write the results in itemsResult only.
Does anyone know why and how I can prevent it ? That itemsWithFilter methods returns the results to itemsResult only
Here is the Fiddle link: https://jsfiddle.net/afdz3yLt/1/
Here is my itemsWithFilter function
itemsWithFilter: function(filter) {
var items = this.items.data;
var result = {}
console.log("Run itemsWithFilter")
Object.keys(items).forEach(key => {
const item = items[key]
console.log(`filter: ${filter}: check item ${item.id} with category id: ${item.category.id}`)
if (item.category.id == filter) {
result[key] = item
}
})
this.itemsResult.data = result
}
Upvotes: 1
Views: 100
Reputation: 2535
Could be that I am understanding the question wrong, but I think what you are meaning to ask is how to use this.items.data
and write the result to this.itemsResult.data
without this.items.data
being updated as well. This is a typical JavaScript thing where a reference to an object always remains intact. What you are looking for (if my assumption about the question is correct) is to clone the this.items.data
object. The best way to do that is
var items = JSON.parse(JSON.stringify(this.items.data))
. More information in these questions:
How to copy JavaScript object to new variable NOT by reference?
What is the most efficient way to deep clone an object in JavaScript?.
Upvotes: 2