sectasy
sectasy

Reputation: 98

Vue sort object data by selected property in table

I get from my api json object list like that:

"object123": {
  "selected": false, 
  "value": 0.54
}, 

In the frontend, I have table where I display this data with checkbox, how to sort this data by this select property? can you give me a small example?

I tried with

sortedData: function() {
  if(this.calculated) {
    return this.calculated.sort(function(a, b) {
      return a.selected > b.selected
    })
  }
}

but then the table is empty.

Upvotes: 0

Views: 654

Answers (1)

bli07
bli07

Reputation: 673

You cannot use the sort() function for an object. In order to make your code work, you should convert this.calculated to an array.

You can use this code snippet to convert the object to an array.

let calculated = {
  "object1": {
    "selected": false,
    "value": 1
  },
  "object2": {
    "selected": false,
    "value": 20
  },
  "object3": {
    "selected": false,
    "value": 4
  },
  "object4": {
    "selected": false,
    "value": 24
  },
  "object5": {
    "selected": false,
    "value": 6
  },
  "object6": {
    "selected": false,
    "value": 0.26
  },
  "object7": {
    "selected": true,
    "value": 1.52
  },
  "object8": {
    "selected": false,
    "value": 0.54
  },
  "object9": {
    "selected": false,
    "value": 4.27
  }
}

let calculatedArray = []

for (const [key, value] of Object.entries(calculated)) {
  calculatedArray.push({
    id: key,
    ...value
  })
}

sortedData = function() {
  if(calculatedArray) {
    return calculatedArray.sort(function(a, b) {
      return b.selected - a.selected
    })
  } else {
    return []
  }
}

console.log(sortedData())
console.log(calculatedArray)

Upvotes: 2

Related Questions