'how to change keys of array
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"
}
]
Solution 1:[1]
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'])
Solution 2:[2]
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)
Solution 3:[3]
Observations :
JSONyou provided is not a validJSON.- result will be an
objectinstead of anarray.
Working Demo :
const arr = [{
"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"
}
];
const obj = {};
arr.forEach((item) => {
obj[item.skipperid] = item
});
console.log(obj)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Kinglish |
| Solution 2 | knicholas |
| Solution 3 | Rohìt JÃndal |
