Search code examples
javascriptarraysobject

How to convert an object to array of multiple objects in javascript


I have an object of data and I want to split it array of objects

let data = {
    "education_center-266": "Software House x",
    "education_center-267": "Learning Academy xyz",
    "end_date-266": "2022-01-26",
    "end_date-267": "2021-01-22",
    "start_date-266": "2021-01-26",
    "start_date-267": "1998-11-26",
    "title-266": "Web Developer",
    "title-267": "Teacher",
}

I tried differents ways but couldn't reach the result I want.. the result should be

[
    {
        id: "266",
        education_center: "Software House x",
        title: "Web Developer",
        start_date: "2021-01-26",
        end_date: "2022-01-26",
    },
    {
        id: "267",
        education_center: "Learning Academy xyz",
        title: "Teacher",
        start_date: "1998-11-26",
        end_date: "2021-01-22",
    },

]

Solution

  • const data = {
        "education_center-266": "Software House x",
        "education_center-267": "Learning Academy xyz",
        "end_date-266": "2022-01-26",
        "end_date-267": "2021-01-22",
        "start_date-266": "2021-01-26",
        "start_date-267": "1998-11-26",
        "title-266": "Web Developer",
        "title-267": "Teacher",
    };
    
    const myObjects = {};
    Object.keys(data).forEach((key) => {
        const splitKey = key.split('-');
        const elemId = splitKey[1];
        const realKey = splitKey[0];
    
        if (!myObjects[ elemId ]) {
            myObjects[ elemId ] = { id: elemId }; // Create entry
        }
        myObjects[ elemId ][ realKey ] = data[ key ]; 
    });
    
    const myID = 266;
    
    // Turn into array
    const myObjectsToArray = Object.values(myObjects);
    // Or use the myObjects as a key/value store with ID as index
    const selectedElement = myObjects[ myID ];
    
    console.log(myObjects);
    console.log(myObjectsToArray);
    console.log(selectedElement);