Search code examples
javascriptarraysjavascript-objects

How to create array out of object entries?


I need help creating a JavaScript object:

I have three fields from the input form in React state object:

{
  calories: "45",
  fats: "56", 
  proteins: "67"
}

I would like to create a new array i.e. nutrientInformation from this data. The output should resemble this:

nutrientInformation: [
  {
    calories: 45
  },
  {
    fats: 56
  },
  {
    proteins: 67
  }
]

Solution

  • const state = { calories: "45", fats: "56", proteins: "67" };
    
    const nutrientInformation = Object.entries(state).map(([key, value]) => ({
      [key]: value
    }));
    
    console.log(nutrientInformation);