0

I am working with JSON data:

[
    {
        "name": "Person1",
        "a_miles": "110 mi"
    },
    {
        "name": "Person2",
        "b_miles": "22 mi"
    },
    {
        "name": "Person3",
        "a_miles": "552 mi"
    }
]

I need to rename a_miles or b_miles to "total" , but can't seem to get .map() to work since it won't allow multiple keys to 1 final key. Each item with have either A or B as well.

This is what I tried so far:

    .data(function(data) {
        console.log('checking for KMs');
        for(key in data) {
            console.log(key);
            if(data[key].includes(' km')){
                console.log('KM found, deleting %s', key)
                delete data[key];
            }
        }
        //console.log(data)
        savedData.push(data);
    })
    .done(function() {
        var formattedJson = savedData.map(({
            name,
            a_miles:total,
            b_miles:total
        }) => ({
            name,
            total

        }));

Maybe I'm over complicating things, I just need to have a total key/value that replaces a or b so it's consistent through the whole array result.

SudoGaron
  • 232
  • 1
  • 15

2 Answers2

1

Actually you can apply a .map to an object, as already answered here.
Here is an example:

a.map(obj => {
  Object.keys(obj).map( key => {
    if (key.match('_miles')){
        obj['total'] = obj[key];
        delete obj[key];
    }
  })
})
console.log(a);
// [ { name: 'Person1', total: '110 mi' },
//  { name: 'Person2', total: '22 mi' },
//  { name: 'Person3', total: '552 mi' } ]

Where a is the array you proposed. Hope it will help

GianAnge
  • 522
  • 2
  • 11
1

Looking at your destructuring, If you JUST want a_miles or b_miles you can use your syntax also just add an OR between them:

.done(function () {
  const formattedJson = savedData.map(({
    name,
    a_miles,
    b_miles
  }) => ({
    name,
    total: a_miles || b_miles

  }))
});
Aritra Chakraborty
  • 9,464
  • 3
  • 18
  • 26