0

I have an array, e.g.

[ { key: 'NAME', value: 'JAY'},
     { key: 'AGE', value: '65'},
     { key: 'YEAR', value: '2017'},
     { key: 'PLACE', value: 'Delhi'},
     { key: 'PLACE', value: 'Mumbai'},
     { key: 'YEAR', value: '2018'}
]

want to convert it to the below List based on the duplicate key

[ { key: 'NAME', value: ['JAY']},
     { key: 'AGE', value: ['65']},
     { key: 'YEAR', value: ['2017','2018']},
     { key: 'PLACE', value: ['Delhi','Mumbai']}
]

Please help ..

4
  • What have you done so far? Commented Oct 16, 2018 at 8:27
  • I converted the values to array from string. Want to achieve this in an optimal way. maybe without using filter/map multiple times Commented Oct 16, 2018 at 8:30
  • You have to include the code on your post :) Commented Oct 16, 2018 at 8:31
  • Please search "Group array of objects based on property" Commented Oct 16, 2018 at 8:32

1 Answer 1

1

You can use reduce method by passing a callback provided function as argument.

var array = [ { key: 'NAME', value: 'JAY'},
     { key: 'AGE', value: '65'},
     { key: 'YEAR', value: '2017'},
     { key: 'PLACE', value: 'Delhi'},
     { key: 'PLACE', value: 'Mumbai'},
     { key: 'YEAR', value: '2018'}
]

let result = array.reduce(function(arr, item){
  let foundElem = arr.find(elem => elem.key === item.key);
  if(!foundElem)
     arr.push({key : item.key, value : [item.value]});  
  else
    foundElem.value.push(item.value);
  return arr;
}, []);
console.log(result);

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

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.