迭代jQuery中的对象数组并匹配属性

时间:2017-08-22 05:50:13

标签: javascript jquery arrays json loops

我正在尝试使用我的循环值使用jQuery循环并分组这个对象数组。

my jsonObj

我希望最终的对象看起来像这样。

  

[       {'组织':'ABC Inc','地址':'123 Front','city':'Wilmington','state':'NC','zip':'09900'},       {'组织':'Wonton Inc','地址':'555 Front','city':'Jasper','state':'NC','zip':'09877'},       {'organization':'ABC Inc','地址':'123 Front','city':'Wilmington','state':'NC','zip':'45345'}   ]

1 个答案:

答案 0 :(得分:1)

使用hash table#reduce()函数提取所需的数据结构 - 请参阅下面的演示:

var object = [{loop:0, key: 'organization', value:'ABC Inc'}, {loop:0,key:'address',value:'123 Front'}, {loop:0, key: 'city',value:'Wilmington'},{loop:0, key:'state',value:'NC'},{loop:0, key:'zip',value:'09900'}, {loop:1,key:'organization',value:'Wonton Inc'},{ loop:1, key:'address',value:'555 Front'}, {loop:1,key:'city',value:'Jasper'},{loop:1, key:'state',value:'NC'},{loop:1, key:'zip',value:'09877'}, {loop:1, key:'organization',value:'ABC Inc'},{loop:1, key:'address',value:'123 Front'},{loop:1, key:'city',value:'Wilmington'},{loop:1, key:'state',value:'NC'},{loop:1, key:'zip',value:'45345'}];

var result = object.reduce(function(hash){
  return function(p,c) {
    if(!hash[c.loop]) {
      hash[c.loop] = {}
      p.push(hash[c.loop]);
    }
    hash[c.loop][c.key] = c.value;
    return p;
  }
}(Object.create(null)), []);

console.log(result);
.as-console-wrapper{top:0;max-height:100%!important;}