开发者

parse json object array by index position

Im working on parsing a json object array so that if the value = 'y', the list of keys is returned as a comma-seperated list that is a variable that will be returned in html.

I want to reference the key/value pairs by index position because I only want to return the values that are the key/values #13-39.

Any suggestions about the best way to go about this is?

I already have a jquery map function to access some of the properties through (ie, obj.address). But I havent been able to successfully use filter or grep to only select the object properties with certain key names or index positions.

This is what the array looks like:

[{"Name": "Name1", "Key1": "Y", 开发者_运维技巧"Key2": "Y", "Key3": "N", "Key4": "Y", "Key5": "N"},
{"Name": "Name2", "Key1": "N", "Key2": "Y", "Key3": "Y", "Key4": "N", "Key5": "N"},
{"Name": "Name3", "Key1": "N", "Key2": "Y", "Key3": "Y", "Key4": "Y", "Key5": "Y"}}

Thanks for any help!


I suppose you can figure out some way to do this using jQuery's $.map, but personally I just find it easier to think of in a pure JavaScript way. (Note that if your keys aren't actually named "Key1", "Key2", etc. but you want to access the keys by their position in an associative array, this has no reliable cross-browser implementation.):

var bar = [
  {"Name": "Name1", "Key1": "Y", "Key2": "Y", "Key3": "N",
                    "Key4": "Y", "Key5": "N"},
  {"Name": "Name2", "Key1": "N", "Key2": "Y", "Key3": "Y",
                    "Key4": "N", "Key5": "N"},
  {"Name": "Name3", "Key1": "N", "Key2": "Y", "Key3": "Y",
                    "Key4": "Y", "Key5": "Y"}
];
var parsed = {}; // this contains the result
var MIN_KEY = 2; // set to 13 for your request
var MAX_KEY = 4; // set to 39 for your request

for (var i = 0, iLen = bar.length; i < iLen; i++) {
  var baz = bar[i];
  var name;
  var temp = [];
  for (var key in baz) {
    var keyNum = parseInt(key.replace("Key", ""));

    // Get the name or add valid key to an array
    if (key === "Name") {
      name = baz[key];
    } else if (baz[key] === "Y" && keyNum >= MIN_KEY && keyNum < MAX_KEY) {
      temp.push(key);
    }
  }

  // Concatenates temp array like "Key1, Key2, Key3"
  parsed[name] = temp.join(", ");
}

console.log(bar);
console.log(parsed);

Alternative implementation by counting keys (note that this may not be reliable across browsers):

for (var i = 0, iLen = bar.length; i < iLen; i++) {
  var counter = 0;
  var baz = bar[i];
  var name;
  var temp = [];
  for (var key in baz) {
    if (key === "Name") {
      name = baz[key];
    } else if (baz[key] === "Y" && counter >= MIN_KEY && counter < MAX_KEY) {
      temp.push(key);
    }
    counter++;
  }
  parsed[name] = temp.join(", ");
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜