1

Hi Guys i need small help in getting this solved.

If this is a duplicate post please point me to the original question.

Here I have an JSON array of elements

Ex : var consume = [{"key":"Test1"},{"key":"Test2"},{"key":"Test3"},{"key":"Test1"},{"key":"Test3"},{"key":"Test1"}];

Expected OutPut:

var produce = [{"name":"test1","count":3},{"name":"test2","count":2},{"name":"test3","count":2}]

2 Answers 2

4

Finally I wrote Answer to my question in pure javascript.

Thanks for your support guys who ever tried to guide me to solve my question

var consume = [{"key":"Test1"},{"key":"Test2"},{"key":"Test3"},{"key":"Test1"},{"key":"Test3"},{"key":"Test1"}]
 
 var temp = [];
 
 var produce = [];
 
 for(var i=0;i<consume.length;i++){
   if(temp.indexOf(consume[i].key) == -1){
   		temp.push(consume[i].key);
      var _data = {};
      _data.name = consume[i].key;
      _data.count = 1;
      
      produce.push(_data);
   }else{
     for(var j=0;j<produce.length;j++){
     		if(produce[j].name === consume[i].key){
        		var _x = parseInt(produce[j].count) + 1;
            produce[j].count = _x;
        }
     }
   }
 }

console.log(produce);

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

Comments

0

Hmm.. these days when it comes to object property thingies i am intrigued with ES6 iterators. This is how i would approach this job;

var consume = [{"key":"Test1"},{"key":"Test2"},{"key":"Test3"},{"key":"Test1"},{"key":"Test3"},{"key":"Test1"}],
    reduced = consume.reduce((p,c) => (p[c.key] ? p[c.key]++ : p[c.key] = 1,p),{}),
    produce = [];
reduced[Symbol.iterator] = function*(){
                             var oKeys = Object.keys(this);
                             for(var key of oKeys) yield {name : key, count: this[key]};
                           };
produce = [...reduced];
console.log(produce);

Comments

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.