Home > Back-end >  How to append different key element of objects in Array?
How to append different key element of objects in Array?

Time:12-12

I need to append different key elements of objects in an array.

I have:

["2022-12-01", "2022-12-02", "2022-12-03", "2022-12-04"]

I need an array like this:

[{
    "2022-12-01": {
      disableTouchEvent: true,
      "selected": true,
      "selectedColor": "#ffff",
      "selectedTextColor": "grey"
    }
  },
  {
    "2022-12-02": {
      disableTouchEvent: true,
      "selected": true,
      "selectedColor": "#3634A3",
      "selectedTextColor": "#ffff"
    }
  },
  {
    "2022-12-03": {
      disableTouchEvent: true,
      customStyles: customDateStyle2,
      "selected": true,
      "selectedColor": "#ffff",
    }
  },
  {
    "2022-12-04": {
      disableTouchEvent: true,
      customStyles: customDateStyles,
      "selected": true,
      "selectedColor": "#ffff",
    }
  }
]

CodePudding user response:

Am not sure if I'm getting the original OP's throughs, but the code can be implemented this way

    let dates = ["2022-12-01", "2022-12-02", "2022-12-03", "2022-12-04"];
    
    
    let details = [{
          disableTouchEvent: true,
          "selected": true,
          "selectedColor": "#ffff",
          "selectedTextColor": "grey"
        },
      {
          disableTouchEvent: true,
          "selected": true,
          "selectedColor": "#3634A3",
          "selectedTextColor": "#ffff"
        }
     ,
     {
          disableTouchEvent: true,
          customStyles: "customDateStyle2",
          "selected": true,
          "selectedColor": "#ffff",
       
      },
       {
          disableTouchEvent: true,
          customStyles: "customDateStyles",
          "selected": true,
          "selectedColor": "#ffff",
        
      }
      ]
    
    let result = dates.map((v, i)=> ({
         [v]: details[i]   
        }) )
    
    console.log(result)

CodePudding user response:

I think mapping dates will do what you want

like this :

const dates = ["2022-12-01", "2022-12-02", "2022-12-03", "2022-12-04"]

   let data = dates.map((date,index)=> ({
     [date]:dataFromBackend[index]   
    }) )
  • Related