-5
MyJsonArray = 
[{quoteId: "MqWmJkUzcP", price: 211, userName: "Test"},{quoteId: "OqgFavcIiR", price: 230, userName: "Aglowid"},{quoteId: "MqWmJkUzcP", price: 120},
 {quoteId: "IFeiWnxMfq", price: 146, userName: "Test-2"},
 {quoteId: "pVL0CgIxaN", price: 155, userName: "Test-2"}]

I want json array like unique this array and create price array inside it like below where quoteId match

Output

[{quoteId: "MqWmJkUzcP", price:[211,120], userName: "Test"},
 {quoteId: "OqgFavcIiR", price: 230, userName: "Aglowid"},
 {quoteId: "IFeiWnxMfq", price: 146, userName: "Test-2"},
 {quoteId: "pVL0CgIxaN", price: 155, userName: "Test-2"}]

Sorry for typing and grammar mistake because i ask this question from mobile

Mark
  • 90,562
  • 7
  • 108
  • 148
shehzad lakhani
  • 495
  • 5
  • 14
  • 1
    Possible duplicate of [What is the most efficient method to groupby on a JavaScript array of objects?](https://stackoverflow.com/questions/14446511/what-is-the-most-efficient-method-to-groupby-on-a-javascript-array-of-objects) – woozyking Sep 20 '18 at 04:05
  • Do really want `price` to be an array sometimes and a number other times? You should consider making them all arrays with some only containing one value. – Mark Sep 20 '18 at 04:06
  • This can be done typically through a technique called "group by", which is offered through quite a few popular utility function libraries such as lodash/underscore. And it's not difficult to implement through `Array.prototype.reduce` method. – woozyking Sep 20 '18 at 04:07
  • The posted question does not appear to include [any attempt](https://idownvotedbecau.se/noattempt/) at all to solve the problem. StackOverflow expects you to [try to solve your own problem first](https://meta.stackoverflow.com/questions/261592/how-much-research-effort-is-expected-of-stack-overflow-users), as your attempts help us to better understand what you want. Please edit the question to show what you've tried, so as to illustrate a specific problem you're having in a [MCVE]. For more information, please see [ask] and take the [tour]. – CertainPerformance Sep 20 '18 at 04:10

1 Answers1

2

This is how you do it in plain javascript (es6)

const mergePrice = data => data.reduce((result, val) => {
   const { quoteId, price, userName } = val;
   let obj = result.find(o => o.quoteId === quoteId);
   if (!obj) {
       obj = { quoteId, userName, price: [] };
       result.push(obj);
   }
   obj.price.push(price);
   return result;
}, []);

const merged = mergePrice([{quoteId: "MqWmJkUzcP", price: 211, userName: "Test"},{quoteId: "OqgFavcIiR", price: 230, userName: "Aglowid"},{quoteId: "MqWmJkUzcP", price: 120},
 {quoteId: "IFeiWnxMfq", price: 146, userName: "Test-2"},
 {quoteId: "pVL0CgIxaN", price: 155, userName: "Test-2"}]);
 
 console.log(merged);
sofyan
  • 76
  • 4