Trying to sort object keys based on child property

3763 views javascript
3

I have this object:

var myObject = {
    cat: {
        order: 1
    },

    mouse: {
        order: 4
    },

    dog: {
        order: 2
    },   

    shark: {
        order: 3
    }
}

I'm trying to get back: ["cat", "dog", "shark", "mouse"]

I tried:

_.sortBy(x, function(e) { return e.order} )

answered question

First you need to get an array.

3 Answers

4

You can simply use Object.keys() and Array.sort() for it.

  • get all the keys from the Object using Object.keys().
  • Simply sort all the keys by passing a custom Comparator to the sort function which compares the order property of the keys in the object.

var myObject = { cat: { order: 1 }, mouse: { order: 4 }, dog: { order: 2 }, shark: { order: 3 } };

let result = Object.keys(myObject).sort((a,b)=> myObject[a].order -  myObject[b].order);

console.log(result);

posted this
12

use Object.entries first, then sort by the order property of its second element (because Object.entries returns an array of a given object's own enumerable property [key, value] pairs), finally use Array.map to get what you need.

var myObject = {
  cat: {
    order: 1
  },
  mouse: {
    order: 4
  },
  dog: {
    order: 2
  },
  shark: {
    order: 3
  }
}

console.log(
  Object.entries(myObject).sort((a, b) => {
    return a[1].order - b[1].order
  }).map(item => item[0])
)

posted this
6

 let oKeys = Object.keys(myObject)

 let tempArray = []

 oKeys.map((key)=>{
    tempArray[key[order]] = key
 })
 console.log(tempArray)

posted this

Have an answer?

JD

Please login first before posting an answer.