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

}

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

1 Comment

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.