1

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?

2
  • So the new data is an array containing one single element with a single categoryAndValueItems property, and this property contains the old data? Commented Aug 24, 2022 at 11:50
  • 1
    Yes essentially Commented Aug 24, 2022 at 11:51

2 Answers 2

7

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 }];
Sign up to request clarification or add additional context in comments.

Comments

0

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.