CODEforDREAM
CODEforDREAM

Reputation: 1083

How to create new array base on JSON value

i have question about array, for example i have an array of object, like this

const data = [
  {
    level: 1,
    name: "Naruto",
  },
  {
    level: 2,
    name: "Dragon",
  },
  {
    level: 2,
    name: "Ball",
  },
  {
    level: 3,
    name: "Sasuke",
  },
] 

Now i want to create new array base on level , mean that after format it will look like this:

[
  [
    {
      name: "naruto"
    }
  ],
  [
    {
      name: "Ball"
    },
    { name: "Dragon" }
  ],
  [
    {name:"Sasuke"}
  ]
];

How can i do this, thanks you guys

Upvotes: 0

Views: 37

Answers (1)

Nick Vu
Nick Vu

Reputation: 15510

I used a loop to handle your case

currentLevel - 1 is mapped with the index of the result's array

const data = [{
    level: 1,
    name: "Naruto",
  },
  {
    level: 2,
    name: "Dragon",
  },
  {
    level: 2,
    name: "Ball",
  },
  {
    level: 3,
    name: "Sasuke",
  },
];

let result = []
for (const currentValue of data) {

  const currentLevel = currentValue.level

  if (!result[currentLevel - 1]) {
    result[currentLevel - 1] = []
  }

  result[currentLevel - 1].push({
     name: currentValue.name
  })
}

//it's followed by index, the result will have some `undefined` if your levels have gaps. You can comment it out, if you want to keep `undefined` values
result = result.filter(item => item)

console.log({
  result
})

Upvotes: 1

Related Questions