0

variable array has multiple objects so i want to merge objects based on repeated id and other values will assign into offer objects how to do that ?.. Thanks in advance

var array = [
   {
      id:1,
      shopname:'star salon',
      offid: 12,
      offname:'100% discount'
   },
   {
      id:1,
      shopname:'star salon',
      offid: 16,
      offname:'Billing Value discount'
   },
   {
      id:3,
      shopname:'trend beauty',
      offid: 19,
      offname:'Percentage Offer'
   }

 ]

And finally out put is given below:

  var result = [
  {
    id:1,
    shopname:'star salon',
    offer : [
      {
        offid: 12,
        offname:'100% discount'
      },
      {
        offid: 16,
        offname:'Billing Value discount'
      }
    ]
  },

  {
    id:3,
    shopname:'trend beauty',
    offer : [
       {
          offid: 19,
          offname:'Percentage Offer'
       }
    ]
  }

 ]
3
  • group by id, or name? Commented Nov 21, 2017 at 21:21
  • group by id and shopname Commented Nov 21, 2017 at 21:21
  • It would be a lot easier if you immediately started off with an array of offers (even if only one). Is that possible? Commented Nov 21, 2017 at 21:24

1 Answer 1

2

You can use this code, which collects the items in a plain object, keyed by id, and then extracts the values from it:

var array = [{id:1,shopname:'star salon',offid: 12,offname:'100% discount'},{id:1,shopname:'star salon',offid: 16,offname:'Billing Value discount'},{id:3,shopname:'trend beauty',offid: 19,offname:'Percentage Offer'}];

var result = Object.values(array.reduce( (acc, {id, shopname, offid, offname}) => {
    acc[id] = acc[id] || { id, shopname, offer: [] };
    acc[id].offer.push({ offid, offname });
    return acc;
}, {}));

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

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.