0

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.

3
  • can you provide an example of multiple objects in the variable calculated? Does it contain an object or an array? Commented Sep 18, 2020 at 12:40
  • Is this.calculated an array of objects? Commented Sep 18, 2020 at 12:40
  • Too long to paste here, pastebin.com/5XSAut8p it is contained in this.calculated Commented Sep 18, 2020 at 12:44

1 Answer 1

2

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)

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

2 Comments

Then when i change selected to true, should be at the first position of array but is in the same order
Thanks!! works fine. I never would have thought of it.

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.