Home > Blockchain >  How to convert an array of objects into an array with one object with the key being fixed and value
How to convert an array of objects into an array with one object with the key being fixed and value

Time:08-24

I have an array like so with each array item being an object and there can be multiple objects:

originalArray = [
    {
        "category": "ASDGFVFG",
        "total": 1
    },
    {
        "category": "DFGH",
        "total": 1
    },
    .........
]

How can I convert it into the following structure? Note that categoryAndValueItems is fixed, so it can be 'hard-coded'.

newData = [{
  categoryAndValueItems: [
    {
        "category": "ASDGFVFG",
        "total": 1
    },
    {
        "category": "DFGH",
        "total": 1
    },
    .........
  ]
}]

I know that I can use .map to create a new array using values in an original array like so:

newArray = originalArray.map(x => ({....}))

I also know that I can use the dot notation or the square bracket notation to create a new key:

obj["categoryAndValueItems"] = ...

However, I'm unsure of how to go further or combine the two, how would I be able to convert the array?

CodePudding user response:

Perhaps you're over-thinking it? It doesn't look like you're converting the array into anything, just setting it as a property on the new object as-is:

let newData = [{ categoryAndValueItems: originalArray }];

CodePudding user response:

I have created a simple snippet, i hope this is what you were looking for...

const originalArray = [
  {
    "category": "ABC",
    "total": 1
  },
  {
    "category": "DEF",
    "total": 2
  },
  {
    "category": "GHI",
    "total": 3
  },
]

let newData = [{ categoryAndValueItems: originalArray }];

console.log(newData)

  • Related