0

I have following code and I was wondering, if that could be solved better? The objective is to move an item within an object up / down.

moveTab = (action, tab) => event => {
    event.stopPropagation();

    let order = { ...this.state.settings.layout }
    let sorted = false;
    let sortedArray = Object.keys(order).sort((a, b) => {

        if (!sorted && ((action === 'up' && b === tab) || (action === 'down' && a === tab))) {
            sorted = true;
            return 1;
        }

        return 0;
    });

    let sortedObject = {}
    sortedArray.map(key => sortedObject[key] = order[key]);

    console.log(order);
    console.log(sortedObject);

    // ... more code ...
}
3limin4t0r
  • 19,353
  • 2
  • 31
  • 52
Zefau
  • 3
  • 3
  • 1
    why would you need to order an object? does not make any sense if you can directly access the key index. If it is in case of displaying it, you could simply have an array ordered and when iterating and displaying forEach through the array and display the object. – iwaduarte Mar 19 '20 at 22:15
  • 1
    JavaScript object properties have complicated ordering (or unordering) rules - I'd say it's best not to depend on it at all. When ordering does matter then use an `Array`: https://stackoverflow.com/questions/5525795/does-javascript-guarantee-object-property-order – Dai Mar 19 '20 at 22:21
  • If you do want to use an object for fast value access, but still want it ordered you can use a separate array that holds the keys in the order you want. For example `obj = {a: 1, b: 2, c: 3}`, `order = ["b", "c", "a"]`. An other solution you see often is to store the position in the object `obj = {a: {position: 2, value: 1}, b: {position: 0, value: 2}, c: {position: 1, value: 3}}`. This solution isn't really handy for scalar values, but if your value is already an complex type you can add one additional field with relative ease. – 3limin4t0r Mar 19 '20 at 22:29

0 Answers0