创建数组时更改键的名称

时间:2012-06-06 09:10:31

标签: javascript jquery arrays solr

在solr查询中执行groupby后,我得到了以下格式的响应。我使用solr版本3.5

"grouped":{
    "channel_id":{
      "matches":48,
      "ngroups":26,
      "groups":[{
          "groupValue":"204",
          "doclist":{"numFound":1,"start":0,"docs":[
              {
                "channel_name":"ZeeTv",
                "channel_num":4,
                "title":"The Name",
                "channel_id":"204"
          }},
        {
          "groupValue":"166",
          "doclist":{"numFound":2,"start":0,"docs":[
              {
                "channel_name":"Sony",
                "channel_num":2,
                "title":"The Name",
                "channel_id":"166",
              {
                "channel_name":"Sony",
                "channel_num":2,
                "title":"The Puzzle",
                "channel_id":"166"
          }}]}}

我按照以下方式在数组中进行响应:

for(var chl in data.grouped.channel_id.groups) {
    config['playlist'].push(data.grouped.channel_id.groups[chl]['doclist']['docs']); 
}

因此形成每个groupValue的单个阵列。阵列的结构是:

"0"=>{"0"=>"value"},"1"=>{"0"=>"result1","1"=>"result2"}

但我想在创建数组时将响应名称即“0”,“1”更改为响应groupValue,以便我可以config['playlist']['166']检查所有节目来自数组的channel_id。可以这样做,如果是这样的话。我期待以下内容:

"204"=>{"0"=>"value"},"166"=>{"0"=>"result1","1"=>"result2"}

如果可能的话,可以进行solr查询,使得响应中的channel_num按升序排列,即第一个结果为channel_num 2然后是4.我已完成groupby:channel_id

2 个答案:

答案 0 :(得分:2)

怎么样?

for(var chl in data.grouped.channel_id.groups) {
    config['playlist'][data.grouped.channel_id.groups[chl].groupValue] = data.grouped.channel_id.groups[chl]['doclist']['docs'];
}

Push是在数组末尾添加元素。但是任何Javascript对象都只是一个哈希表,所以你可以这样使用它。

顺便说一句,您可以使用for each

使代码更简单
for each(var chl in data.grouped.channel_id.groups) {
    config['playlist'][ch1.groupValue] = ch1['doclist']['docs'];
}

答案 1 :(得分:2)

Pikrass已正确回答...就channel_num订购而言,请尝试在查询中添加以下内容:

&sort=channel_num asc