Chris Frank
Chris Frank

Reputation: 4442

Add object key to each item in object array

I have a payload coming back from an endpoint like this:

const charges = [
    {
        'id': 'someId',
        'dates': ['2017-11-11', '2017-12-11'],
    },
    {
        'id': 'anotherId',
        'dates': ['2017-09-11', '2017-10-11'],
    },
];

What would be the best way to attach id to each of the items in the dates array so that it results in this:

[
    { id: 'someId', date: '2017-11-11' },
    { id: 'someId', date: '2017-12-11' },
    { id: 'anotherId', date: '2017-09-11' },
    { id: 'anotherId', date: '2017-10-11' },
]

I've tried something like this:

let history = [];
charges.map(charge => (
    charge.dates.map((date) => (
        history.concat({
            id: charge.payerCode,
            date: date,
        })
    ))
));

But history is not defined in the scope I'm using it in.

I know there is probably a better way to do this, but I just can't seem to wrap my head around it.

Any help would be greatly appreciated!

Thanks!

Upvotes: 3

Views: 115

Answers (6)

Nina Scholz
Nina Scholz

Reputation: 386550

You could Array#reduce while concat all objects, build with dates arrays.

let charges = [{ id: 'someId', dates: ['2017-11-11', '2017-12-11'] }, { id: 'anotherId', dates: ['2017-09-11', '2017-10-11'] }],
    result = charges.reduce((r, { id, dates }) => r.concat(dates.map(date => ({ id, date }))), []);

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

Edge version, which prevents (it might be a bug inside of Edge)

SCRIPT5113: Use before declaration
result = charges.reduce((r, { id, dates }) => r.concat(dates.map(date => ({ id, date }))), []);
                                                                            ^

const
    charges = [{ id: 'someId', dates: ['2017-11-11', '2017-12-11'] }, { id: 'anotherId', dates: ['2017-09-11', '2017-10-11'] }],
    result = charges.reduce((r, a) => r.concat(a.dates.map(d => ({ id: a.id, date: d }))), []);

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

Upvotes: 3

prasanth
prasanth

Reputation: 22490

Try with Array#reduce recreate the array and Array#forEach to iterate the inner array

const charges = [{'id': 'someId', 'dates': ['2017-11-11', '2017-12-11'],}, { 'id': 'anotherId','dates': ['2017-09-11', '2017-10-11'],},];

var res = charges.reduce(function(a,b){
b.dates.forEach(function(n){
a.push({id:b.id,dates:n})
})
return a;
},[])

console.log(res)

ES6

const charges = [{'id': 'someId', 'dates': ['2017-11-11', '2017-12-11'],}, { 'id': 'anotherId','dates': ['2017-09-11', '2017-10-11'],},];

var res = charges.reduce((a,b) =>(b.dates.forEach(d=>a.push({id:b.id,dates:d})),a),[])

console.log(res)

Upvotes: 0

Ben Aston
Ben Aston

Reputation: 55729

const charges = [
    {
        'id': 'someId',
        'dates': ['2017-11-11', '2017-12-11'],
    },
    {
        'id': 'anotherId',
        'dates': ['2017-09-11', '2017-10-11'],
    },
];

function flatten(charges) {    
  return charges.reduce((p, {id, dates}) => 
           (dates.forEach(date => p.push({id, date})), p), []);    
}

console.log(flatten(charges))

Upvotes: 3

Nofi
Nofi

Reputation: 2175

$(document).ready(function(){
    const charges = [
    {
        'id': 'someId',
        'dates': ['2017-11-11', '2017-12-11'],
    },
    {
        'id': 'anotherId',
        'dates': ['2017-09-11', '2017-10-11'],
    },
];
var temp={};
var finalArray = [];
for(ch in charges){
    for(dt of charges[ch]['dates']){
        temp.id = charges[ch]['id'];
        temp.date =dt;
        finalArray.push(temp);
        temp={};
    }
}
console.log(JSON.stringify(finalArray));
});

Upvotes: 0

castletheperson
castletheperson

Reputation: 33466

A simple imperative solution would be:

const history = [];
for (const { payerCode, dates } of charges) {
  for (const date of dates) {
    history.push({ id: payerCode, date });
  }
}

Upvotes: 1

abhishekkannojia
abhishekkannojia

Reputation: 2856

You can use Array#reduce in combination with Array#concat like this :

const charges = [
    {
        'id': 'someId',
        'dates': ['2017-11-11', '2017-12-11'],
    },
    {
        'id': 'anotherId',
        'dates': ['2017-09-11', '2017-10-11'],
    },
];

var r = charges.reduce(function(acc, obj) {
  return acc.concat(obj.dates.map(function(date) {
    return {
      id : obj.id,
      date : date
    };
  }))
}, []);

console.log(r);

Upvotes: 1

Related Questions