0

I have an array of object like this:

[
  {
    header: {
      car: 'Start',
      carName: startName
    },
    data: [ [Object], [Object], [Object] ]
  },
  {
    header: {
      car: 'End',
      carName: endName
    },
    data: [ [Object], [Object], [Object] ]
  },
  {
    header: {
      car: 'Finish',
      carName: finishName
    },
    data: [ [Object], [Object], [Object] ]
  }
]

Where startName, endName, and finishName are function references. I want to replace the whole array with actually calling the function so it should be like this:

[
  {
    header: {
      car: 'Start',
      carName: startName()
    },
    data: [ [Object], [Object], [Object] ]
  },
  {
    header: {
      car: 'End',
      carName: endName()
    },
    data: [ [Object], [Object], [Object] ]
  },
  {
    header: {
      car: 'Finish',
      carName: finishName()
    },
    data: [ [Object], [Object], [Object] ]
  }
]

I thought of creating some sort of mapping function and new object but looks like its too much. Is there a simpler way to do it?

bjb568
  • 11,089
  • 11
  • 50
  • 71
nativeGuy
  • 33
  • 3
  • In the fisrt object (let's name it `obj`) if called `obj.header.startName` it will call the function `startName` with no problem – First dev May 13 '21 at 21:35

1 Answers1

0

Your second block of code is completely valid. You can assign the return of the startName, endName and finishName functions called respectively for each object's attribute carName.

If you want to declare them as function references and then replace them with their returning values later in the code, you can do:

let modified = arrayOfValues.map(value => {
  value.header.carName = value.header.carName();
  return value;
})

Assuming arrayOfValues is the whole array in the example.

Important note: take in account that the original arrayOfValues will also be modified (e.g to have carName attribute value replaced), since map does not make a deep copy of the original array and header is a sub-document. If you want to keep the original arrayOfValues intact, you'll have to use a library (e.g lodash). More on the discussion in this question.

GusSL
  • 652
  • 7
  • 23
  • Thanks GusSL that works! I want to do the same for data which is array of objects. I am assuming we can just do the same logic for that as well. – nativeGuy May 13 '21 at 22:51
  • @nativeGuy absolutely. It will work as well. Don't forget to mark the answer as accepted if it solved your question. – GusSL May 13 '21 at 23:32