如何更改对象中嵌套对象的索引

时间:2019-06-03 09:56:56

标签: javascript arrays json object nested-object

我试图找到一种方法来更改对象的索引,该对象还有一些其他对象也带有键。 假设我想将键传递给函数3(C),然后在与3(C)相同的对象中找到键,并将其索引设置为0

我尝试使用hasOwnProperty,但是当我通过3(C)时,它始终只为true。我尝试了大多数事情,但是在嵌套数组的情况下失败了

{
  "1(C)": {
    "STORE (06:00 )": [
      {
        "personId": "---",
        "scheduledEventId": "----",
        "employeeName": "----.",
        "phoneNumber": "-----",
        "ranking": "-----",
        "perAph": "----",
        "distPerAph": "--",
        "distanceToEvent": "0"
      }
    ]
  },
"3(C)": {
    "THUdx (06:00 )": [
      {
        "personId": "---",
        "scheduledEventId": "----",
        "employeeName": "----.",
        "phoneNumber": "-----",
        "ranking": "-----",
        "perAph": "----",
        "distPerAph": "--",
        "distanceToEvent": "0"
      }
    ]
  }
}

预期结果应在索引0处包含3(C)对象

{
"3(C)": {
    "THUdx (06:00 )": [
      {
        "personId": "---",
        "scheduledEventId": "----",
        "employeeName": "----.",
        "phoneNumber": "-----",
        "ranking": "-----",
        "perAph": "----",
        "distPerAph": "--",
        "distanceToEvent": "0"
      }
    ]
  },
  "1(C)": {
    "STORE (06:00 )": [
      {
        "personId": "---",
        "scheduledEventId": "----",
        "employeeName": "----.",
        "phoneNumber": "-----",
        "ranking": "-----",
        "perAph": "----",
        "distPerAph": "--",
        "distanceToEvent": "0"
      }
    ]
  }
}

1 个答案:

答案 0 :(得分:0)

您可能以错误的方式做某事,并且不可能按照标准去做您想完成的事情。

但是,至少在Chrome中,对象中的键顺序似乎是通过定义键的顺序来定义的,这可以通过创建新对象,首先复制要在第0个位置的成员来实现,然后复制所有剩余的成员。

function moveToFirst(src, key) {
  var keys = Object.keys(src);
  var temp = {};
  temp[key] = src[key];
  for (var k = 0; k < keys.length; ++k){
    if (keys[k] !== key) {
      temp[keys[k]] = src[keys[k]];
    }
  }
  return temp;
}
var foo = {c: "1", a: 5, bar: "lol"}
foo = moveToFirst(foo, "a");  // {a: 5, c: "1", bar: "lol"}