Attach a new property to a specific location in an object

If I attach an additional property to an object, does it need to go at the end or can I put it at a specified position.

function reassign(obj){
  delete obj.c;
  obj.c = "new three";

  var t = "<table border=\"1\">";
  for (var i in obj){
    t += "<tr><td>" + obj[i] + "</td></tr>"; 
  }
  t += "</table>";
  return t;
}

var obj = {
  a : "one",
  b : "two",
  c : "three",
  d : "four" 
};

var reassigned = reassign(obj);
document.write(reassigned);

      

Is there some way to put the new one back obj.c

at the third position after removing it rather than adding it to the end? Of course, I could have missed the removal part. But even without that, I might, for example, intend to enter alphabeta: "one point five"

into the second position. Is it possible? Thank!

jsbin

+3


source to share


2 answers


The elements of the array are ordered; there are no object properties. You should never assume that the properties of an object will repeat in a particular order.

If order is important to you, create a new property order:[]

that contains an array of property names and you can iterate through this:



var obj = {
  a : "one",
  b : "two",
  c : "three",
  d : "four",
  order : ['a','b','c','d']
};

      

+2


source


The objects are out of order. You can create an array and split your object into key-value pairs, or you can use an array to index the keys of the objects.

Option 1

var collection = [
  {key1: value1},
  {key2: value2},
  {key3: value3}
];

      

Option 2



var obj = {
  key1: value1,
  key2: value2,
  key3: value3
};

// you can index just the values
var index_to_value = [
  obj['key1'],
  obj['key2'],
  obj['key3']
];

// or you can index by key, if necessary
var index_to_key = [
  'key1', 'key2', 'key3'
];

      

And of course, if it doesn't get in the way, you can put the index on the object:

var obj = {
  key1: value1,
  key2: value2,
  key3: value3,
  _index: [
    'key1', 'key2', 'key3'
  ]
};

      

And I would recommend using sort and compare or splice function to manipulate the index.

+1


source







All Articles