Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

convert array object to another

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading