0

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,
  },
];
2
  • 1
    @felixkling recursion is overkill for this. It just needs a simple map. const result = currentArray.map(({year, asset}) =>({year, ...asset})); Commented Sep 23, 2021 at 11:45
  • @pilchard, perfect))) Commented Sep 23, 2021 at 11:50

1 Answer 1

1

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)

Sign up to request clarification or add additional context in comments.

1 Comment

Even easier: Object.assign(item, item.asset). But if you mutate the array, don't use .map.