User
User

Reputation: 60

Change position of a javascript object

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

Upvotes: 1

Views: 532

Answers (1)

Peleg Haham
Peleg Haham

Reputation: 91

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)

Upvotes: 2

Related Questions