javascript - sort object by key by using lodash but key has lost after sorted - Stack Overflow

admin2025-04-19  0

I want to sort some Object look likes this

data = {
        "imH3i4igFNxM3GL": {
            "name": "Nacky",
            "age": 12
        },
        "vuzPuZUmyT8Z5nE": {
            "name": "Emmy",
            "age": 20
        },
        "OkIPDY1nGjxlq3W": {
            "name": "Nat",
            "age": 20
        }
}

I want to sort it by "name". I tried to use Lodash for this problem.

_.sortBy(data, [function(o) { return o.name; }]);

but, it return me an array of objects without the keys

[
    {
      "name": "Emmy",
      "age": 20
    },
    {
      "name": "Nacky",
      "age": 12
    },
    {
      "name": "Nat",
      "age": 20
    }
]

I want it return me sorted object with key like the same

{
    "vuzPuZUmyT8Z5nE": {
        "name": "Emmy",
        "age": 20
    },
    "imH3i4igFNxM3GL": {
        "name": "Nacky",
        "age": 12
    },
    "OkIPDY1nGjxlq3W": {
        "name": "Nat",
        "age": 20
    }
}

what should I do? thanks

I want to sort some Object look likes this

data = {
        "imH3i4igFNxM3GL": {
            "name": "Nacky",
            "age": 12
        },
        "vuzPuZUmyT8Z5nE": {
            "name": "Emmy",
            "age": 20
        },
        "OkIPDY1nGjxlq3W": {
            "name": "Nat",
            "age": 20
        }
}

I want to sort it by "name". I tried to use Lodash for this problem.

_.sortBy(data, [function(o) { return o.name; }]);

but, it return me an array of objects without the keys

[
    {
      "name": "Emmy",
      "age": 20
    },
    {
      "name": "Nacky",
      "age": 12
    },
    {
      "name": "Nat",
      "age": 20
    }
]

I want it return me sorted object with key like the same

{
    "vuzPuZUmyT8Z5nE": {
        "name": "Emmy",
        "age": 20
    },
    "imH3i4igFNxM3GL": {
        "name": "Nacky",
        "age": 12
    },
    "OkIPDY1nGjxlq3W": {
        "name": "Nat",
        "age": 20
    }
}

what should I do? thanks

Share asked May 8, 2017 at 16:25 NutAnekNutAnek 211 gold badge1 silver badge3 bronze badges 2
  • You're not sorting an array; you're trying to sort an object. This is generally a bad idea, since iterating over the object is not guaranteed to output the keys in the order you want see this ment on a similar question – Heretic Monkey Commented May 8, 2017 at 16:42
  • Well, _.sortBy accepts an object but will return an array, as per the doc. As Mike says, you cannot get an object with "sorted" keys. – Hugues M. Commented May 8, 2017 at 16:45
Add a ment  | 

2 Answers 2

Reset to default 3

Objects in JS can't be sorted, and the order of the properties is not reliable, ie it depends on browsers' implementations. That's why _.sortBy() is converting your object into a sorted array.

I can think of 2 options to work with that.

Add the key to the objects in the array

If you just need an ordered array with the keys in the objects, so you can render a list.

var data = {
        "imH3i4igFNxM3GL": {
            "name": "Nacky",
            "age": 12
        },
        "vuzPuZUmyT8Z5nE": {
            "name": "Emmy",
            "age": 20
        },
        "OkIPDY1nGjxlq3W": {
            "name": "Nat",
            "age": 20
        }
};

var result = _(data)
  .map(function(v, k) { // insert the key into the object
    return _.merge({}, v, { key: k });
  })
  .sortBy('name') // sort by name
  .value();
  
console.log(result);
<script src="https://cdnjs.cloudflare./ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>

Create an order array

Create an array of ordered keys, and use them when you wish to render the objects in order.

var data = {
        "imH3i4igFNxM3GL": {
            "name": "Nacky",
            "age": 12
        },
        "vuzPuZUmyT8Z5nE": {
            "name": "Emmy",
            "age": 20
        },
        "OkIPDY1nGjxlq3W": {
            "name": "Nat",
            "age": 20
        }
};

var orderArray = _(data)
  .keys() // create an array of keys
  .sortBy(function(key) { // sort the array using the original names
    return data[key].name;
  }) // sort by name
  .value();

console.log('The order array', orderArray);

console.log(orderArray.map(function(k) {
  return data[k];
}));
<script src="https://cdnjs.cloudflare./ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>

I use something like this.

    let data = {
    'g34ghgj3kj': {
        YOUR_KEY: 'g34ghgj3kj',
        'key1': false,
        'key2': false,
    },
    'hh334h664': {
        YOUR_KEY: 'hh334h664',
        'key1': true,
        'key2': false,
    },
    //{...}
};

_.orderBy(data, ['key1', 'key2'], ['desc', 'desc']).reduce((result, value) => {
    result[value.YOUR_KEY] = value;
    return result;
}, {});

转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1745071919a283332.html

最新回复(0)