1

I am working on a javascript object. And I want to change the sequence of the object.

This is my current object(I'm trying to move the last two key, value pairs of the object),

const obj = {
  one: {
    name: "one"
  },
  two: {
    name: "two"
  },
  five: {
    name: "five"
  },
  three: {
    name: "three"
  },
  four: {
    name: "four"
  }
};

This is what I'm trying to achieve,

const obj = {
  one: {
    name: "one"
  },
  two: {
    name: "two"
  },
  three: {
    name: "three"
  },
  four: {
    name: "four"
  }
  five: {
    name: "five"
  },
};

This is so far what I've done,

const numbers = ["one", "two", "three"];

const sortObject = (object) => {
  let objOne = {};
  let objTwo = {};
  let index = 0;

  Object.entries(object).forEach(([key, value]) => {
    if (numbers.includes(key)) {
      objOne[key] = value;
    } else {
      objTwo[key] = value;
    }
  });

  for (const obj in objOne) {
    if (index === 2) {
      Object.assign(objOne, objTwo);
    }
    index++;
  }

  Object.entries(objOne).forEach((element) => {
    console.log(element);
  });
};

sortObject(obj);

Would it be possible to move the last two key, value pairs of the object to the third position of the object?

codepen

User
  • 60
  • 1
  • 9
  • 7
    the order of keys in an object should not be important to you - if it is important, then you're using the wrong data structure – Jaromanda X Sep 25 '22 at 07:33
  • 2
    Use an array instead of an object if you'd like to reorder them – evolutionxbox Sep 25 '22 at 07:35
  • Related question: [Does JavaScript guarantee object property order?](https://stackoverflow.com/questions/5525795/does-javascript-guarantee-object-property-order) – Yogi Sep 25 '22 at 07:55

1 Answers1

2

Hope it will be helpful.

const obj = {
  one: {
    name: "one"
  },
  two: {
    name: "two"
  },
  five: {
    name: "five"
  },
  three: {
    name: "three"
  },
  four: {
    name: "four"
  }
};
let newObj = Object.fromEntries(Object.entries(obj).sort(sorter));
function sorter(a,b){
    //a[1] and b[1] is the value of the obj, a[0] is the key.
    let item = a[1].name;
    let nextItem = b[1].name;
    const sorterDict = {"one":0,"two":1,"three":2,"four":3,"five":4};
    if(sorterDict[item] > sorterDict[nextItem])
        return 1;
    else if(sorterDict[item] < sorterDict[nextItem])
        return -1;
    return 0;
}
console.log(newObj)
  • Note that even if this works in some examples, there is no guarantee whatsoever that this will always work, given that objects in Javascript are unordered. It may fail on some browsers, on some devices, with large objects, if there is not much memory available, and so on. – Guillaume Brunerie Sep 25 '22 at 07:54