1

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

}
user7646471
  • 352
  • 3
  • 11

1 Answers1

2

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?.

Imre_G
  • 2,468
  • 1
  • 17
  • 33
  • you are a hero. it works if I parse the object.. don't understand the reference thing but will check your link. very strange tho. – user7646471 Nov 04 '17 at 19:46