1

I'm trying to loop and group through this object array using jQuery using my loop value.

my jsonObj

I'd like the final object to look like this.

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

3
  • 1
    Post the original object and the loop script you used to console log each attributes. Maybe there is not much missing to group them. Commented Aug 22, 2017 at 5:56
  • please do not post images of code.... Commented Aug 22, 2017 at 6:02
  • I meant to simplify since the code is very complicated. @LouysPatriceBessette Commented Aug 22, 2017 at 12:18

1 Answer 1

1

Use a hash table and #reduce() function to extract the data structure required - see demo below:

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;}

Sign up to request clarification or add additional context in comments.

1 Comment

I accepted your answer. Thanks it worked exactly they way I wanted it to

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.