将JSON解析为子集

时间:2015-02-26 15:12:56

标签: javascript json

以下是我的JSON字符串,我想在客户端将其解析为3个不同的列名(MAT_ETHNICITY,PAT_ETHNICITY,SEX),因此我可以将值放入每列的下拉列表中。我应该只做三个单独的SQL调用并通过三个不同的服务器调用发送它,解析服务器端或通过循环解析客户端?感谢

[
    {
        "REFCODE": "HIS",
        "DESCRIPTION": "Hispanic or Latino",
        "COLUMN_NAME": "MAT_ETHNICITY"
    },
    {
        "REFCODE": "NHIS",
        "DESCRIPTION": "Not Hispanic or Latino",
        "COLUMN_NAME": "MAT_ETHNICITY"
    },
    {
        "REFCODE": "UNK",
        "DESCRIPTION": "Unknown",
        "COLUMN_NAME": "MAT_ETHNICITY"
    },
    {
        "REFCODE": "AMERIND",
        "DESCRIPTION": "American Indian/Alaska Native",
        "COLUMN_NAME": "PAT_ETHNICITY"
    },
    {
        "REFCODE": "ASIAN",
        "DESCRIPTION": "Asian",
        "COLUMN_NAME": "PAT_ETHNICITY"
    },
    {
        "REFCODE": "HAW",
        "DESCRIPTION": "Native Hawaiian or Other Pacific Islander",
        "COLUMN_NAME": "PAT_ETHNICITY"
    },
    {
        "REFCODE": "AA",
        "DESCRIPTION": "Black or Africian American",
        "COLUMN_NAME": "PAT_ETHNICITY"
    },
    {
        "REFCODE": "WHITE",
        "DESCRIPTION": "White",
        "COLUMN_NAME": "PAT_ETHNICITY"
    },
    {
        "REFCODE": "MORE",
        "DESCRIPTION": "More than one race",
        "COLUMN_NAME": "PAT_ETHNICITY"
    },
    {
        "REFCODE": "UNK",
        "DESCRIPTION": "Unknown",
        "COLUMN_NAME": "PAT_ETHNICITY"
    },
    {
        "REFCODE": "M",
        "DESCRIPTION": "Male",
        "COLUMN_NAME": "SEX"
    },
    {
        "REFCODE": "F",
        "DESCRIPTION": "Female",
        "COLUMN_NAME": "SEX"
    }
]

4 个答案:

答案 0 :(得分:1)

您应该尽量减少对服务器的调用次数,以帮助加快您的网站速度。将它解析为三个不同的数组很容易在JavaScript中完成。

var data = [...], // This is the array you have up top
    refCodes = [],
    descriptions = [],
    columns = [],
    parseData;

parseData = function () {
    var ref,
        desc,
        col,
        i,
        l;

    for (i = 0, l = data.length; i < l; i++) {
        ref = data[i]['REFCODE'];
        desc = data[i]['DESCRIPTION'];
        col = data[i]['COLUMN_NAME'];

        if ($.inArray(ref, refCodes) === -1) {
            refCodes.push(ref);
        }
        if ($.inArray(desc, descriptions) === -1) {
            descriptions.push(desc);
        }
        if ($.inArray(col, columns) === -1) {
            columns.push(col);
        }
    }
};

这将为您提供每个数组中的唯一值。

答案 1 :(得分:1)

我使用数组映射:

var refArr = jsonObj.map(function(ele){return ele.REFCODE;})
var descArr = jsonObj.map(function(ele){return ele.DESCRIPTION;})
var colNameArr = jsonObj.map(function(ele){return ele.COLUMN_NAME;})

每个map调用都将遍历您返回的JSON数组,然后获取值并将它们放入相应的数组中。

<小时/> 编辑: 但是,根据你的评论,我相信我们都认为你问的不同于你想要的东西。您的意见

  

... SEX,PAT_ENTICITY和MAT_ETHNICITY,而不是REFCODE,DESCRIPTION和COLUMN_NAME。所以我最终会得到sexArr = [&#34;女性&#34;,&#34;男性&#34;]和MAT_ETHNICITY将是var matArr = [&#34;西班牙裔或拉丁裔&#34;,&#34;不是西班牙裔或拉丁裔&#34;]等?或正在循环最好的

可能 .map这些值数组,但是如果使用映射则必须删除未定义的或空的字符串值,因为映射将返回相同数量的元素。您要映射的数组。

您希望使用类似于以下内容的.forEach(...)进行迭代:

var sexArr = [];
var patArr = [];
var matArr = [];

jsonObj.forEach(function(ele){
  switch(ele.COLUMN_NAME){
    case "SEX":
      sexArr.push(ele.DESCRIPTION);
      break;
    case "PAT_ETHNICITY":
      patArr.push(ele.DESCRIPTION);
      break;
    case "MAT_ETHNICITY":
      matArr.push(ele.DESCRIPTION);
      break;
    default:
      //do nothing, or handle as you see fit.
      break;
  }
});

此代码根据您提供的数组生成以下内容:

//matArr
["Hispanic or Latino", "Not Hispanic or Latino", "Unknown"]

//patArr
["American Indian/Alaska Native", "Asian", "Native Hawaiian or Other Pacific Islander", "Black or Africian American", "White", "More than one race", "Unknown"]

//sexArr
["Male", "Female"]

答案 2 :(得分:1)

This answer解释了一种可以适应您案例的技术

&#13;
&#13;
var data = [{"REFCODE":"HIS","DESCRIPTION":"Hispanic or Latino","COLUMN_NAME":"MAT_ETHNICITY"},{"REFCODE":"NHIS","DESCRIPTION":"Not Hispanic or Latino","COLUMN_NAME":"MAT_ETHNICITY"},{"REFCODE":"UNK","DESCRIPTION":"Unknown","COLUMN_NAME":"MAT_ETHNICITY"},{"REFCODE":"AMERIND","DESCRIPTION":"American Indian/Alaska Native","COLUMN_NAME":"PAT_ETHNICITY"},{"REFCODE":"ASIAN","DESCRIPTION":"Asian","COLUMN_NAME":"PAT_ETHNICITY"},{"REFCODE":"HAW","DESCRIPTION":"Native Hawaiian or Other Pacific Islander","COLUMN_NAME":"PAT_ETHNICITY"},{"REFCODE":"AA","DESCRIPTION":"Black or Africian American","COLUMN_NAME":"PAT_ETHNICITY"},{"REFCODE":"WHITE","DESCRIPTION":"White","COLUMN_NAME":"PAT_ETHNICITY"},{"REFCODE":"MORE","DESCRIPTION":"More than one race","COLUMN_NAME":"PAT_ETHNICITY"},{"REFCODE":"UNK","DESCRIPTION":"Unknown","COLUMN_NAME":"PAT_ETHNICITY"},{"REFCODE":"M","DESCRIPTION":"Male","COLUMN_NAME":"SEX"},{"REFCODE":"F","DESCRIPTION":"Female","COLUMN_NAME":"SEX"}];

function shallowClone(obj, exclude) {
  var clone = {};
  for (var prop in obj) {
    if (prop != exclude) {
      clone[prop] = obj[prop];
    }
  }
  return clone;
}

function mapFromArray (list , keyByProp, excludeKeyByProp) {
  var map = {};
  for (var i=0, item; item = list[i]; i++) {
    if ( !map[item[keyByProp]] ) {
      map[item[keyByProp]] = [];
    }
    map[item[keyByProp]].push(item);
  }
  
  if (excludeKeyByProp) {
    for (var prop in map) {
      map[prop] = map[prop].map(function(obj){
        return shallowClone(obj, keyByProp);
      });
    }
  }
  return map;
};


var separated = mapFromArray(data, 'COLUMN_NAME', true);
console.log(separated);
var pre = document.body.appendChild(document.createElement('pre'));
pre.innerHTML = JSON.stringify(separated, null, 2);
&#13;
&#13;
&#13;

在您在评论中解释输出所需内容之前,我已回答此问题

krillgar's answer有效。这是一个不是O(n2)并且不包含重复的。

var data = [/*your data */];
var refCodes = {}, descriptions = {}, columns = {};
for (var i = 0; i < data.length; i++) {
    refCodes[data[i].REFCODE] = true;
    descriptions[data[i].DESCRIPTION] = true;
    columns[data[i].COLUMN_NAME] = true;
}

refCodes = Object.keys(refCodes);
descriptions = Object.keys(descriptions);
columns = Object.keys(columns);

这是该代码的概括

&#13;
&#13;
var data = [{"REFCODE":"HIS","DESCRIPTION":"Hispanic or Latino","COLUMN_NAME":"MAT_ETHNICITY"},{"REFCODE":"NHIS","DESCRIPTION":"Not Hispanic or Latino","COLUMN_NAME":"MAT_ETHNICITY"},{"REFCODE":"UNK","DESCRIPTION":"Unknown","COLUMN_NAME":"MAT_ETHNICITY"},{"REFCODE":"AMERIND","DESCRIPTION":"American Indian/Alaska Native","COLUMN_NAME":"PAT_ETHNICITY"},{"REFCODE":"ASIAN","DESCRIPTION":"Asian","COLUMN_NAME":"PAT_ETHNICITY"},{"REFCODE":"HAW","DESCRIPTION":"Native Hawaiian or Other Pacific Islander","COLUMN_NAME":"PAT_ETHNICITY"},{"REFCODE":"AA","DESCRIPTION":"Black or Africian American","COLUMN_NAME":"PAT_ETHNICITY"},{"REFCODE":"WHITE","DESCRIPTION":"White","COLUMN_NAME":"PAT_ETHNICITY"},{"REFCODE":"MORE","DESCRIPTION":"More than one race","COLUMN_NAME":"PAT_ETHNICITY"},{"REFCODE":"UNK","DESCRIPTION":"Unknown","COLUMN_NAME":"PAT_ETHNICITY"},{"REFCODE":"M","DESCRIPTION":"Male","COLUMN_NAME":"SEX"},{"REFCODE":"F","DESCRIPTION":"Female","COLUMN_NAME":"SEX"}];

function makeArraysFromProps(data) {
  var map = {};
  for (var i = 0; i < data.length; i++) {
    var keys = Object.keys( data[i] );
    for (var j = 0; j < keys.length; j++ ) {
      var key = keys[j];
      if (!map[key]) {
        // Make it a map first to prevent duplicates without O(n2)
        map[key] = {};
      }
      map[key][ data[i][key] ] = true;
    }
  }
  var mapKeys = Object.keys(map);
  for (var k=0; k < mapKeys.length; k++) {
    map[mapKeys[k]] = Object.keys(map[mapKeys[k]]);
  }
  return map;
}


var separated = makeArraysFromProps(data);
console.log(separated);
var pre = document.body.appendChild(document.createElement('pre'));
pre.innerHTML = JSON.stringify(separated, null, 2);
var separated = makeArraysFromProps(data);
console.log(separated);

document.body.appendChild(document.createTextNode(JSON.stringify(separated)))
&#13;
&#13;
&#13;

答案 3 :(得分:0)

我会用一个SQL调用来解析并解析客户端。当你在一次通话中得到你需要的东西时,进行三次单独的通话毫无意义。

只需遍历每个对象,然后获取所需的属性,并将其粘贴到使用Javascript的下拉列表中。

我希望这是一个足够的答案。

编辑: 这是一种提取可以使用的数据的方法。然后,您可以使用不同的值填充对象,并在任何您想要的地方循环。

var json = YOURJSONOBJECT;

var patObj = new Object;

json.forEach(function(data, i){ 
  if(data.COLUMN_NAME == 'PAT_ETHNICITY') {
    patObj[i] = { refCode: data.REFCODE, description: data.DESCRIPTION }
  }
  // Then add rest of your columns
});