在嵌套对象中的相同索引处删除和添加对象

时间:2015-01-07 18:54:56

标签: javascript

对象:

var userData = {
  "a1":{"a":"1"},
  "b2":{"b":"2"},
  "c3":{"c":"3"},
  "d4":{"d":"4"},
  "e5":{"e":"5"},
};

我需要用键“a1”删除Object并在同一个地方放置一个新对象,即“f6” 即

userData["f6"] = userData["a1"];
userData["f6"].new = "true"; 
delete userData["a1"];  

输出:

userData = {
  "b2":{"b":"2"},
  "c3":{"c":"3"},
  "d4":{"d":"4"},
  "e5":{"e":"5"},  
  "f6":{"a":"1", new:true},
};   

预期的O / p:

var userData = {
  "f6":{"a":"1", new:true},
  "b2":{"b":"2"},
  "c3":{"c":"3"},
  "d4":{"d":"4"},
  "e5":{"e":"5"},
};   

先谢谢..

1 个答案:

答案 0 :(得分:1)

在Javascript中,对象没有特定的属性顺序。当您将它们视为JSON时,属性将按照声明或添加的顺序显示。要保留特定订单,您可以对对象进行更改并实施Array