0
var data = [
    { 'Promotions 1': 2192, 'dates': '2021-02-04' },
    { 'Promotions 23': 767, 'dates': '2021-02-06' },
    { 'Promotions 12': 2264,'dates': '2021-02-08' },
];

The Issue is Promotions are dynamic key only access dates key-value. I want output like this below. I want that on unique every dates with all promotions Expected Output

var totalUserJoined = [
    { 
        'Promotions 1': 2192,
        'Promotions 23': 767,
        'Promotions 12': 2264 ,
        'dates': '2021-02-04'
    },
    { 
        'Promotions 1': 2192,
        'Promotions 23': 767,
        'Promotions 12': 2264 ,
        'dates': '2021-02-06'
    },
    { 
       'Promotions 1': 2192,
        'Promotions 23': 767,
        'Promotions 12': 2264 ,
        'dates': '2021-02-08'
    }
];

2
  • 1
    What did you try? What did go wrong? Commented Mar 4, 2021 at 8:47
  • Object.keys(data) / Object.entries(data) Commented Mar 4, 2021 at 8:51

1 Answer 1

2

You can use .map() and destructuring assignment to get all keys other than dates into their own object. Once you have an array of objects only containing the promotion keys (ie: the none dates), you can merge them all together using Object.assign() to form one object. Then you can use .map() on your original data array to merge the promotions object with every date:

const data = [ { 'Promotions 1': 2192, 'dates': '2021-02-04' }, { 'Promotions 23': 767, 'dates': '2021-02-06' }, { 'Promotions 12': 2264,'dates': '2021-02-08' }, ];

const promotions = Object.assign(...data.map(({dates, ...rest}) => rest));
const res = data.map(({dates}) => ({...promotions, dates}));

console.log(res);

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

1 Comment

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.