5

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?

15
  • 2
    objects do not have order - so it doesn't matter... Commented Aug 20, 2017 at 16:33
  • Objects are different than arrays, its properties do not have a particular order, so it cannot be done. Commented Aug 20, 2017 at 16:34
  • 1
    Since ES6, object properties have a guaranteed order. Commented Aug 20, 2017 at 16:35
  • @ssube: That's not quite right: stackoverflow.com/q/30076219/218196 Commented Aug 20, 2017 at 16:37
  • Guaranteed order for for ... in or Object.keys came with ecmascript2017. ES6 allows for terrible pitfalls. Commented Aug 20, 2017 at 16:37

3 Answers 3

12

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);

Sign up to request clarification or add additional context in comments.

3 Comments

This solves the question, but what if there were non-enumerable properties (or getter/setter)?
@ASDFGerte, i would not rely on a order of an object. Object.assign copies only own enumerable properties.
This did not work: disease_dict.assign({Select: "<td><div class='custom-control custom-checkbox'>" + "<input type='checkbox' class='custom-control-input'" +"id='customCheck1' name=${" + check_name + "}>" +"<label class='custom-control-label' for='customCheck1'>" + "</label></div></td>", disease_dict });
5

I tried, It works with spread operator. Do it in below way

var object = { last_name: "john", age: 23, city: "London" };
var newObject= { first_name: "Samuel" };
object = {...newObject, ...object }

o/p: { first_name: "Samuel", last_name: "john", age: 23, city: "London" };

Comments

0

Can do with spread operator, not confident about order

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

var newObj={first_name: "Samuel" ,... object}

console.log(newObj);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.