0

I'm using the following getter in my Vuex store to get the datasets from my state.

getDatasets: state => {
    let datasets = [];
    state.observations.forEach(obs => {
      if (!datasets.includes(obs.dataset)) {
        datasets.push(obs.dataset);
      }
    })
    return datasets;
  }

However, this return as many datasets as observations in my state whereas it should return only one dataset.

I believe this is due to the __obs__ field added by VueJs that is different for each dataset object.

Did I misunderstood something and how could I fix this?

1 Answer 1

1

It's not the issue with vuex/vue. By checking datasets.includes(obs.dataset)), you are actually check if datasets contains any object that have same reference with obs.dataset, which is inevitably false.

A very simple example can be ran in browser console to replicate your logic:

var state = { observations: [ { dataset: {}}, { dataset: {}} ]}
var datasets = []
state.observations.forEach(function(obs) {
    if (!datasets.includes(obs.dataset)) {
        datasets.push(obs.dataset);
    }
})
console.log(datasets.length) // 2, not 1
console.log(datasets[0] === state.observations[0].dataset) // true, same reference
console.log(datasets[0] === state.observations[1].dataset) // false

If you want to get unique values of datasets, try comparing parsed string of object instead:

state.observations.forEach(obs => {
    if (!datasets.some(
        elem => SON.stringify(elem) === JSON.stringify(obs.dataset))
    ) {
        datasets.push(obs.dataset);
    }
})
Sign up to request clarification or add additional context in comments.

Comments

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.