0

This is essentially what the payload looks like from my API. I'd like to reshape the data so I can dynamically display the data on the frontend without hard coding things like column names. For what it's worth I'm using DRF, axios, and react-redux. That said I think I just need to learn more vanilla js :/

*purposely have a different number of keys in 1 entry vs another.

data =[
{
    "id": 1,
    "j_column": {
        "name": "James",
        "outside_id": 1,
        "alt_name": "Jim",
        "full_name": "James the third"
    }
},
{
    "id": 3,
    "j_column": {
        "name": "Dennis",
        "outside_id": 57,
        "alt_name": "Denny",
        "full_name": "Dennis the third",
        "nickname": "Denny the super star"
    }
}]



newData =[
{
    "id": 1,
    "name": "James",
    "outside_id": 1,
    "alt_name": "Jim",
    "full_name": "James the third"
},
{
    "id": 3,
    "name": "Dennis",
    "outside_id": 57,
    "alt_name": "Denny",
    "full_name": "Dennis the third",
    "nickname": "Denny the super star"
}]
DerC
  • 1
  • 2

2 Answers2

0

This is one way to do it:

const data =[
  {
      "id": 1,
      "j_column": {
          "name": "James",
          "outside_id": 1,
          "alt_name": "Jim",
          "full_name": "James the third"
      }
  },
  {
      "id": 3,
      "j_column": {
          "name": "Dennis",
          "outside_id": 57,
          "alt_name": "Denny",
          "full_name": "Dennis the third",
          "nickname": "Denny the super star"
      }
}];

const newData = data.map((el) => {
  const obj = {...el.j_column};
  obj.id = el.id;
  return obj;
});

console.log(newData);
alotropico
  • 1,904
  • 3
  • 16
  • 24
0
var new_data = [];
data.map(item => {
    var obj = {};
    Object.keys(item).map(itemKey => {
        if (typeof item[itemKey] !== 'object') {
            obj[itemKey] = item[itemKey]
        }else
            Object.keys(item[itemKey]).map(subItemKey => {
                obj[subItemKey] = item[itemKey][subItemKey]
            })
    })
    new_data.push(obj);
})
console.log(new_data);
JB_DELR
  • 737
  • 1
  • 4
  • 7