I want to convert this:
[
{
"company": "test"
},
{
"block": "test"
},
{
"start_date": "15/08/2023 15:00"
},
{
"end_date": "15/08/2023 15:00"
},
{
"company": "test1"
},
{
"block": "test1"
},
{
"start_date": "15/08/2023 15:00"
},
{
"end_date": "15/08/2023 15:00"
}
]
to this:
[
{
"company": "test",
"block": "test",
"start_date": "15/08/2023 15:00",
"end_date": "15/08/2023 15:00"
},
{
"company": "test1",
"block": "test1",
"start_date": "15/08/2023 15:00",
"end_date": "15/08/2023 15:00"
}
]
How to convert like that?
>Solution :
You can get the first key in the array and iterate the array with creation new result objects when this key is encountered:
const [startKey] = Object.keys(arr[0]);
const result = [];
let obj;
for(const item of arr){
const [[key, val]] = Object.entries(item);
key === startKey ? result.push(obj = {[key]: val}) : obj[key] = val;
}
console.log(result);
<script>
const arr = [
{
"company": "test"
},
{
"block": "test"
},
{
"start_date": "15/08/2023 15:00"
},
{
"end_date": "15/08/2023 15:00"
},
{
"company": "test1"
},
{
"block": "test1"
},
{
"start_date": "15/08/2023 15:00"
},
{
"end_date": "15/08/2023 15:00"
}
]
</script>