Home > Software engineering >  how to change keys of array
how to change keys of array

Time:02-04

I have the following array of objects. How do I change the keys of the array (0,1) to the skipperid (217,1)

[0:
        {
            "type": "RES",
            "date": "2022-05-14",
            "doy": 133,
            "skipperid": 217,
            "boat": "Laura",
            "start": "09:00:00",
            "end": "22:00:00",
            "spots": 5,
            "fname": "David",
            "lname": "Cross"
        }, 
     1:{
            "type": "SAIL",
            "date": "2022-05-14",
            "doy": 133,
            "skipperid": 1,
            "boat": "Avrora",
            "start": "10:00:00",
            "end": "13:00:00",
            "spots": 3,
            "fname": "Bob",
            "lname": "Smith"
        }
    ]

CodePudding user response:

Javascript arrays always have numeric indexes. If you want to have keys, you'll need to convert into an object as shown here.

let data = [{
    "type": "RES",
    "date": "2022-05-14",
    "doy": 133,
    "skipperid": 217,
    "boat": "Laura",
    "start": "09:00:00",
    "end": "22:00:00",
    "spots": 5,
    "fname": "David",
    "lname": "Cross"
  },
  {
    "type": "SAIL",
    "date": "2022-05-14",
    "doy": 133,
    "skipperid": 1,
    "boat": "Avrora",
    "start": "10:00:00",
    "end": "13:00:00",
    "spots": 3,
    "fname": "Bob",
    "lname": "Smith"
  }
]

data = data.reduce((b,a) => ({...b, [a.skipperid]:a}), {});
console.log(data['217'])

CodePudding user response:

I definitely suggest using an object like @Kinglish example.

Moving the position from current index to index by skipperid creates an array of size (highest skipperid), leaving all index != skipperid as undefined

USE AN OBJECT

This is messy:

let data = [{
    "type": "RES",
    "date": "2022-05-14",
    "doy": 133,
    "skipperid": 217,
    "boat": "Laura",
    "start": "09:00:00",
    "end": "22:00:00",
    "spots": 5,
    "fname": "David",
    "lname": "Cross"
  },
  {
    "type": "SAIL",
    "date": "2022-05-14",
    "doy": 133,
    "skipperid": 1,
    "boat": "Avrora",
    "start": "10:00:00",
    "end": "13:00:00",
    "spots": 3,
    "fname": "Bob",
    "lname": "Smith"
  }
]
data.forEach((o,i,self)=> {
if(o?.skipperid != i){
self[o.skipperid] = o;
self[i] = undefined
}
})
console.log(data)

  •  Tags:  
  • Related