Beginner_Hello
Beginner_Hello

Reputation: 367

How to convert an array of objects into an array with one object with the key being fixed and value being all original objects?

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?

Upvotes: 0

Views: 49

Answers (2)

Boguz
Boguz

Reputation: 1823

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)

Upvotes: 0

David
David

Reputation: 218808

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 }];

Upvotes: 7

Related Questions