This is my input:
sampleDataSet = [{
"-1":"default",
"CreatedDate":"2024-03-13T13:43:58.000Z"
}, {
"-2":"defaultMain",
"CreatedDate":"2024-03-14T18:44:02.000Z"
}, {
"4daasdasd15sdasdasd":"test1",
"CreatedDate":"2024-03-14T15:44:04.000Z"
}, {
"41dasd51asda5d1sd":"test2",
"CreatedDate":"2024-03-15T13:44:06.000Z"
}, {
"sdadsadsad561652165":"test3",
"CreatedDate":"2024-02-16T13:44:08.000Z"
}]
I want to sort above array by created date.
after sort I can get this output:
sampleDataSet = [
{
"sdadsadsad561652165": "test3",
"CreatedDate": "2024-02-16T13:44:08.000Z"
}{
"-1": "default",
"CreatedDate": "2024-03-13T13:43:58.000Z"
},
{
"4daasdasd15sdasdasd": "test1",
"CreatedDate": "2024-03-14T15:44:04.000Z"
},
{
"-2": "defaultMain",
"CreatedDate": "2024-03-14T18:44:02.000Z"
},
{
"41dasd51asda5d1sd": "test2",
"CreatedDate": "2024-03-15T13:44:06.000Z"
}
]
The I wanted to build single object like this
{"sdadsadsad561652165":"test3","-1":"default","4daasdasd15sdasdasd":"test1","-2":"defaultMain","41dasd51asda5d1sd":"test2"}
This is what I tried:
let res = {};
sampleDataSet.forEach(obj => {
const key = Object.keys(obj)[0];
const value = obj[key];
res[key] = value;
})
console.log(res)
but this what I get
{"4daasdasd15sdasdasd":"test1","-1":"default","-2":"defaultMain","41dasd51asda5d1sd":"test2""sdadsadsad561652165":"test3"}
Why is that happening How can I fix that ?
2
Answers
that’s not a good practice nor a good question but anyways, you’re new, here you go
CreatedDate
CreatedDate
with destructuring and useObject.assign
to collect remaining item props into the final result.Note that though it’s not recommended to rely on prop order in an object the order’s kinda preserved de-facto.
Except positive integers which is sorted and put first (I guess that’s done for array-like objects). Or strings representing them. So make sure your integers are negative.
If you want sorted props with positive integers AND the same object property access syntax you could try to use
Proxy
to wrapMap
(note that we changed negative integers to positive ones):