rikg93
rikg93

Reputation: 1269

Move key/value in Javascript Object

I've a problem: i would like to move a key/value of an object by one position, I'm using Javascript, i could also use Lodash, but i cannot transform the object into an array.

My object

"input": {
            "10_": "ab",
            "20_": "cd",
            "30_": "ef"
          }

Result

"input": {
            "20_": "cd",
            "10_": "ab",
            "30_": "ef"
          }

Thank you.

Upvotes: 5

Views: 7271

Answers (3)

Ranjith
Ranjith

Reputation: 157

Positioning of object values have no impact in the Object and how it's properties and methods called. The object properties and methods are called and set only by their keys.

Upvotes: 0

XingZhi Lim
XingZhi Lim

Reputation: 131

An object is unlike an array, the order does not matter.

When retrieving data from an array, you might need to iterate through the entire array. But for an object that has key-value pairs, you just need to access the value using the key.

For example, to access the value of _10 (below), you just have to write fruits.a or fruits['a']

const fruits = {
            'a': 'apple' ,
            'b': 'banana'
          };

const fruits2 = {
            'b': 'banana',
            'a': 'apple' 
          };

JavaScript treats both objects the same way and you get the same output when you do fruits.a and fruits2.a

Upvotes: 0

Krzysztof Krzeszewski
Krzysztof Krzeszewski

Reputation: 6714

In javascript object property order is equivalent to insertion order for string keys and ascending order for number keys, that being the case you can simply insert them in an order you want to obtain a desired result

const input = {
  "10_": "ab",
  "20_": "cd",
  "30_": "ef"
}

console.log({"20_": input["20_"],"10_": input["10_"],"30_": input["30_"]})

or slightly more general

const input = {
  "10_": "ab",
  "20_": "cd",
  "30_": "ef",
  "40_": "ef",
  "50_": "ef"
}

const [firstKey, secondKey] = Object.keys(input);
const {[firstKey]: firstKeyValue, [secondKey]: secondKeyValue, ...rest} = input

console.log({[secondKey]: secondKeyValue, [firstKey]: firstKeyValue, ...rest })

Upvotes: 1

Related Questions