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?
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With