2

I want to merge JSON arrays' some object which have duplicate values of specific key.

I have json Array Like this:

var data=[
    { type:"XO",
      logID:"213323",
      user:"34324234"
    },
    { type:"YO",
      logID:"2323323",
      user:"1212234"
    },
    { type:"XO",
      logID:"676323323",
      user:"45465412234"
    },
    ,
    { type:"ZO",
      logID:"1231434323",
      user:"35739434"
    }
]

Here I want to merge JSON Objects based on key 'type'. so same type will look like this with new key:

var expectedOutput:[
     { 
        type:XO,
        text: [
            {
              logID:"213323",
              user:"34324234"
            },
            {
              logID:"676323323",
              user:"45465412234"
            }
        ]
     },
     { type:"YO",
       text:[
         {
         logID:"2323323",
         user:"1212234"
        }  
      ]
     },
     {
       type:"ZO",
       text:[ 
           {
             logID:"1231434323",
             user:"35739434"
           } 
        ]
     }
]

1 Answer 1

2

You can use lodash#groupBy to group the collection by type, use lodash#map to transform each group object format into a group array format. To remove the type property from the array of text, we'll use a partailly applied lodash#omit function using lodash#partial.

var result = _(data)
  .groupBy('type')
  .map(function(group, type) {
    return {
      type: type,
      text: _.map(group, _.partial(_.omit, _, 'type'))
    };
  })
  .value();

var data = [{
    type: "XO",
    logID: "213323",
    user: "34324234"
  },
  {
    type: "YO",
    logID: "2323323",
    user: "1212234"
  },
  {
    type: "XO",
    logID: "676323323",
    user: "45465412234"
  },
  {
    type: "ZO",
    logID: "1231434323",
    user: "35739434"
  }
];

var result = _(data)
  .groupBy('type')
  .map(function(group, type) {
    return {
      type: type,
      text: _.map(group, _.partial(_.omit, _, 'type'))
    };
  })
  .value();
  
console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>

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

1 Comment

I'ts because your input after the third item of the array is empty. I'll remove that from the input. You will notice that there are two commas "," after the third item in your data input.

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.