skip to Main Content

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


  1. that’s not a good practice nor a good question but anyways, you’re new, here you go

    let result = {}
    let data = [
        { '-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' },
    ]
    for (let obj of data) {
        let key = Object.keys(obj)[0]
        result[key] = obj[key]
    }
    console.log(result)
    Login or Signup to reply.
    1. Sort the array by CreatedDate
    2. Reduce it to an object with removing CreatedDate with destructuring and use Object.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.

    const 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"
      }]
    
    const result = sampleDataSet
      .sort(({CreatedDate: a}, {CreatedDate: b}) => a > b ? 1 : a < b ? -1 : 0)
      .reduce((r, {CreatedDate, ...item}) => Object.assign(r, item), {});
      
    console.log(result);

    If you want sorted props with positive integers AND the same object property access syntax you could try to use Proxy to wrap Map (note that we changed negative integers to positive ones):

    const Obj = new Proxy(Object, {
      apply(_, __, args){
        return new Obj(...args);
      },
      construct(_, args){
        const obj = Reflect.construct(...arguments);
        const map = new Map;
        
        for(const arg of args){
          for(const key in arg){
           map.set(key, arg[key]);
          }
        }
        
        return new Proxy(obj, {
          getOwnPropertyDescriptor(_, prop) {
            return { configurable: true, enumerable: true, value: map.get(prop) };
          },
          ownKeys(){
             return [...map.keys()];
          },
          get(_, prop){
            if(prop === Symbol.iterator){
              return map.keys.bind(map);
            }
            if(prop in obj){
              return obj[prop];
            }
            return map.get(prop);
          },
          set(_, prop, value){
            map.set(prop, value);
            return true;
          }
        });
      }
    
    });
    
        const 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"
          }]
    
        const result = sampleDataSet
          .sort(({CreatedDate: a}, {CreatedDate: b}) => a > b ? 1 : a < b ? -1 : 0)
          .reduce((r, {CreatedDate, ...item}) => Object.assign(r, item), Obj({}));
          
        console.log(result);
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search