aman
aman

Reputation: 6262

JS: Finding next key in json

I have the following json:

{0: "2", 1: "2", $$hashKey: "object:35", undefined: "1"}

Currently I am trying to get its key-value with the below code:

   var data = JSON.stringify(row);
   var result = $.parseJSON(data);
       $.each(result, function (k, v) {
                //display the key and value pair
                console.log(k, v);
       });

The above code works fine and I can get my key-value from it.

Now what I am trying to get is the next key-value pairs within the $.each loop.

For example if in the loop the current key is "0" I want to get the next key "1" in the same call itself. If in the loop the current key is "1" I want to get the next key "$$hashKey" along with their values.

Is it possible to do so? I am open to code changes above if required.

Upvotes: 0

Views: 1895

Answers (3)

Tom O.
Tom O.

Reputation: 5941

You could turn your object into an iterable and which will return the next [key, value] pair each time you call next on the iterator:

function makeIterable(o) {
  o[Symbol.iterator] = () => {
    var keys = Object.keys(o);
    var i = 0;
    return {
      next() {
        var done = false;
        var value = [keys[i + 1], o[keys[i + 1]]];
        if (i >= (keys.length - 1)) {
          done = true;
        }

        i++;

        return {
          value,
          done
        }
      }
    };
  }
}

var jsonStr = '{ "0": "2", "1": "2", "$$hashKey": "object:35", "undefined": "1" }';

var obj = JSON.parse(jsonStr);
makeIterable(obj);

var itr = obj[Symbol.iterator]();
while (true) {
  var item = itr.next();
  if (item.done) {
    break;
  }
  console.log(item.value);
}

Upvotes: 0

danh
danh

Reputation: 62676

Understanding now that the goal is to retrieve keys in the order they appear in JSON, a couple of thoughts:

(1) if you control the source of the object ("row" in the OP code), don't represent it as an object. instead use an array of key-value pairs: [[0, "2"], [1, "2"], [$$hashKey, "object:35"], [undefined, "1"]].

otherwise, (2) roll your own JSON parser that returns an array of key-value pairs for an object. This post looks to be a sensible start. Or, you can vastly simplify the task if you are able to make certain assumptions about the values, for example, say you know that all values are strings...

// parse a string representing an object, returning an array of key-value pairs.
// assumes values are strings that do not contain commas or colons

function myProbablyNegligentlySimpleJSONParse(string) {
    let trimmed = string.trim().slice(1, -1);
    let components = trimmed.split(',');
    return components.map(kvString => {
        let kv = kvString.split(':');
        return [ kv[0].trim(), kv[1].trim()  ];
    });
}

forEach passes the current index to the iterator function, so that int can be used to look ahead or behind in the iteration.

var data = '{0: "2", 1: "2", $$hashKey: "object:35", undefined: "1"}';
let result = myProbablyNegligentlySimpleJSONParse(data);
result.forEach(function (pair, index) {
    let [k, v] = pair;  // now k and v are your key and value
    console.log(`key is ${k} value is ${v}`)
    if (index < result.length-1) {
        let [nextK, nextV] = result[index+1];
        console.log(`next key is ${nextK} next value is ${nextV}`);
    }
});   

Upvotes: 1

tymeJV
tymeJV

Reputation: 104785

You can use Object.keys to get the keys to an array, then run through it with a forEach to have access to the keys index. Important to note that objects are unordered, so your key order one time may differ from the next time:

var keys = Object.keys(obj);
keys.forEach(function(key, index) {
    var nextIndex = index + 1;
    if (nextIndex === keys.length) return; //out of bounds
    var nextKey = keys[nextIndex];
});

Edit: As pointed out by the comments - if you want the keys in the same order each time, call .sort() on your keys array with your desired sort logic.

Upvotes: 3

Related Questions