Home > OS >  Split an array into an array with different objects
Split an array into an array with different objects

Time:01-11

I was working on a plain array but I want the structure of the array to be in a sub-array form with multiple entries inside it. I tried forEach but when I push the element the whole array is pushed inside the sub-array. The array that I have

data = ["1640662522","1640663240","1640663967","1640664659","1640665388","1640666124","1640666829","1640667505","1640668278","1640668984"];

but I want the structure of my new array to be

    {
"sizeData":[
 {
           "timestamp":1640662522,
           "size":12345,
           "fees":12589,
           "cost":168
},
 {
           "timestamp":1640663240,
           "size":12345,
           "fees":12589,
           "cost":168},
 {
           "timestamp":1640663967,
           "size":12345,
           "fees":12589,
           "cost":168
}, {
           "timestamp":1640664659,
           "size":12345,
           "fees":12589,
           "cost":168
}
]

Could anyone help me on this. I am working on js for this

CodePudding user response:

Just do it.

Step 1: Create new array elements

Step 2: ForEach data and push data to array elements

Step 3: Standardized data.

Good luck!

let data = ["1640662522","1640663240","1640663967","1640664659","1640665388","1640666124","1640666829","1640667505","1640668278","1640668984"];
let elements = [];
data.forEach(function(val){
  elements.push({
    "timestamp":parseInt(val),
    "size":12345,
    "fees":12589,
    "cost":168
  })
})
let result = {
  "sizeData": elements 
}
console.log(result) 

  •  Tags:  
  • Related