Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

136
Views
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

almost 4 years ago · Santiago Trujillo
1 answers
Answer question

0

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)

almost 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!