Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add key/value pair in Javascript object at the start

Tags:

javascript

I have following object:

var obj = {"last_name": "john", "age": 23, "city": "London"}

I want to add a new element of first_name at the start of this object to look like this:

{"first_name": "Samuel", "last_name": "john", "age": 23, "city": "London"}

I know I can do obj.first_name = "Samuel" but it adds the new element at the end of the object. How can I add it at the start?

like image 218
Hannan Avatar asked Dec 05 '22 13:12

Hannan


1 Answers

While objects have actually (ES5) no order, you could generate a new object with Object.assign and use the new property as object to start with and assign the given object to it. The new object has properties in creation order.

var object = { last_name: "john", age: 23, city: "London" };

object = Object.assign({ first_name: "Samuel" }, object);

console.log(object);
like image 65
Nina Scholz Avatar answered Jan 02 '23 04:01

Nina Scholz