-2

I have an object as

const details = {
  firstName: "Priya",
  age: 26,
  class: 12,
  Address: "UP",
  lastName: "Kumari"
}

Can I position the "lastName" key just after the "firstName" so that the new created object is :

const updated = {
  firstName: "Priya",
  lastName: "Kumari",
  age: 26,
  class: 12,
  Address: "UP"
}

I tried few methods but read that positioning of object items is not possible

mplungjan
  • 169,008
  • 28
  • 173
  • 236
ashika
  • 47
  • 6
  • You can access it directly from the object. You don't need to apply anything for the position. Is there any specific use case that you are trying? – mc-user Jun 28 '22 at 07:14
  • @mc-user I need to loop through the object to display each key and value in a table, where the lastName should come after firstName and its a huge list of item(this is just a small example) so i dont want to write each key statically. – ashika Jun 28 '22 at 07:19
  • Maybe you can map a key to a specific table column and access it using `data[column].` You already know the table columns and what needs to be displayed. Try to map like that. – mc-user Jun 28 '22 at 07:28
  • Please visit [help], take [tour] to see what and [ask]. Do some research, search for related topics on SO; if you get stuck, post a [mcve] of your attempt, noting input and expected output, preferably in a [Stacksnippet](https://blog.stackoverflow.com/2014/09/introducing-runnable-javascript-css-and-html-code-snippets/) – mplungjan Jun 28 '22 at 07:33

2 Answers2

0

Try converting the object to an array and then use the splice() function

OmarMazin
  • 1
  • 2
  • Please use the *Post answer* button only for actual answers. You should modify your original answer with an example. You can format code when you use the `[<>]` snippet editor – mplungjan Jun 28 '22 at 07:33
0

You can create a new object, say newDetails based on the properties of the details object. We can use destructuring to get the firstName, lastName and all other properties. We'd then create the new object from these.

It's worth noting that we shouldn't rely too much on the order of object properties, since this can change.

const details = { firstName: "Priya", age: 26, class: 12, Address: "UP", lastName: "Kumari"};

const { firstName, lastName, ...otherDetails} = details;

const newDetails = { firstName, lastName, ...otherDetails };

console.log('New details:', newDetails)
.as-console-wrapper { max-height: 100% !important; }
Terry Lennox
  • 29,471
  • 5
  • 28
  • 40