Home > Blockchain >  How to move object properties inside an array of objects [duplicate]
How to move object properties inside an array of objects [duplicate]

Time:09-23

I have an array of objects like this:

currentArray = [
  {
    year: 2011,
    asset: {
      silver: 322,
      gold: 325,
    },
  },
  {
    year: 2012,
    asset: {
      silver: 411,
      gold: 2235,
    },
  },
];

What needs to be done in JavaScript/TypeScript, to change it from the current structure to the structure below? The silver- and gold-property of each asset-object should be stored in the object above, next to 'year', and the asset-objects need to be deleted:

desiredArray = [
  {
    year: 2011,
    silver: 322,
    gold: 325,
  },
  {
    year: 2012,
    silver: 411,
    gold: 2235,
  },
];

CodePudding user response:

let currentArray = [{
    year: 2011,
    asset: {
      silver: 322,
      gold: 325,
    },
  },
  {
    year: 2012,
    asset: {
      silver: 411,
      gold: 2235,
    },
  },
];

currentArray.map(item => {
  Object.assign(item, item.asset)
  delete item.asset;
  
  return item
})

console.log(currentArray)

  • Related