0

I am trying to figure out a way to change the index of an object which has some other objects also with keys. suppose I want to pass key to a function as 3(C) then I want to find a key in an object which is same as 3(C) and make its index as 0

I tried to use hasOwnProperty but it always gives me only true when I pass 3(C). I tried most of the things but it fails in case of nested arrays

{
  "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"
      }
    ]
  }
}

The expected result should have 3(C) object at index 0

{
"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 Answers1

0

You are probably doing something in the wrong way, and it would not be possible to do what you are trying to accomplish according to standards.

However, at least in Chrome, where order of keys in objects seems to be defined by order of defining the keys, something like that is possible by creating a new object, copying the member you want to have at 0th position first, and then copying all the remaining members.

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"}
BoltKey
  • 1,994
  • 1
  • 14
  • 26