SachiDangalla SachiDangalla - 1 month ago 10
Javascript Question

Add attribute to JS object specific place

I want to add attribute to a JS object, but in a custom place, After a given attribute.

var me = {
name: "myname",
age: "myage",
bday: "mybday"
};
me["newAt"] = "kkk"; //this adds at the end of the object


Is there a way to specify the object (
me
), an attribute(
age
) in it and add a new attribute(
newAt
) right after the specified one? A better way than doing string operations?

var newMe = {
name: "myname",
age: "myage",
newAt: "newAttr",
bday: "mybday"
}


UPDATE: (Since people are more focused on why I'm asking this than actually answering it)
I'm working on a drawable component based on user input - which is a JS object. And it has the ability to edit it - so when the user adds a new property based on "add new node" on the clicked node, and I was thinking of adding the new node right after it. And I want to update the data accordingly.

Answer

The simplest solution I could find was to iterate through the keys of the parent and keep pushing them to form a clone of the parent. But to additionally push the new object if the triggered key is met.

var myObj = {
  child1: "data1",
  child2: "data2",
  child3: "data3",
  child4: "data4"
};

var a = (function addAfterChild(data, trigChild, newAttribute, newValue) {
  var newObj = {};
  Object.keys(data).some(function(k) {
    newObj[k] = data[k];
    if (k === trigChild) {
      newObj[newAttribute] = newValue;
    }
  });
  return newObj;
})(myObj, "child3", "CHILD", "VALUE");

document.getElementById("result").innerHTML = JSON.stringify(a);
<p id="result"></p>