Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

how to convert a items in a object to list of array

{
    Type: "Fire",
    Name: "Shark",
    StartRange0: "10",
    EndRange0: "20",
    StartRange1: "30",
    EndRange1: "40",
    StartRange2: "60",
    EndRange2: "70"
}

In the above object, StartRange and EndRange can be more items in different objects. i.e those values are obtained from a loop( StartRange + index), so there maybe StartRange1,2,3… lly, EndRange1,2,3…

The above object structure must be changed to,

{
   "Fire":{
      "Name":"Shark",
      "List":[
         [
            "10",
            "20"
         ],
         [
            "30",
            "40"
         ],
         [
            "60",
            "70"
         ]
      ]
   }
}

The List array inside the object is combination of [StartRange0,EndRange0],[StartRange1,EndRange2]… So on…

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I tried,

let newObj = {}
newObj[oldObj.Type] = {
    Name: oldObj.Name, //oldObj is the first object defined above.
    List: [[oldObj.StartRange0,oldObj.EndRange0],[oldObj.tartRange1,oldObj.EndRange1],[oldObj.StartRange2,oldObj.EndRange2]]
}

But here, it is limited to StartRange2 and EndRange2 but I need it for StartRangeN and EndRangeN.

>Solution :

This is how I would have done map it

const input = {
  Type: "Fire",
  Name: "Shark",
  StartRange0: "10",
  EndRange0: "20",
  StartRange1: "30",
  EndRange1: "40",
  StartRange2: "60",
  EndRange2: "70"
}

const toList = (l) => Array.from({
  length: Object.keys(l).length / 2
}, (_, N) => [l[`StartRange${N}`], l[`EndRange${N}`]])

const toOutput = ({ Type, Name, ...rest }) => {
  const List = toList(rest)
  return ({
    [Type]: {
      Name,
      List
    }
  })
}

const output = toOutput(input)
console.log(output)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading