Add object key to every item in object array

I have a payload returning from an endpoint, for example:

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 bind id

to each element of the array dates

so that it turns out like 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 the story is not defined in the area in which I use it.

I know there is probably the best way to do this, but I just can't wrap my head around me.

Any help would be greatly appreciated!

Thank!

+3


source to share


6 answers


You can Array#reduce

while concat all objects, build with arrays of dates.

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; }
      

Run codeHide result


Edge version that prevents (this could be a bug inside 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; }
      

Run codeHide result


+3


source




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))
      

Run codeHide result


+3


source


You can use Array # shrink 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);
      

Run codeHide result


+1


source


Simple imperative solution:

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

      

+1


source


Try to Array#reduce

recreate the array and Array#forEach

to iterate over 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)
      

Run codeHide result


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)
      

Run codeHide result


0


source


$(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));
});

      

0


source







All Articles