Tadewos Bellete
Tadewos Bellete

Reputation: 49

how do you convert javascript object with arrays in to array of objects with corresponding name and value?

Fellow programmer here, for some reason I have spent two days but I cannot do this properly so help me out. I have an object with arrays for each key like this:

var arraysObject = {
    "North American": [
        "CONUS",
        "NAMER",
        "CONUS/AK",
        "US-NC",
        "US-NE",
        "US-NW",
        "US-SC",
        "US-SE"
    ],
    "Oconus": [
        "ALASKA",
        "GUAM",
        "HAWAII",
        "POLAR",
        "US-SAMOA"
    ],
 }

I have a list of areas that have been selected, like the following

var listOfAreas = ["CONUS", "GUAM","US-SAMOA"]

I want to create the following object:

var result = [{
        "North American":"CONUS",
        "Oconus": "GUAM"
        },
        {
        "North American": "",
        "Oconus":"US-SAMOA"
        }]
        
            

Notice how it created a new object only when that last one's key is full and fills the object if possible. in my implementation it creates an object for each individual string and assigns it to the key using then pushes it using .map This doesn't work. I want it to fill each object accordingly and create an new object only when it is necessary. Appreciate your help. Best, A dummy.

Upvotes: 1

Views: 50

Answers (1)

Nina Scholz
Nina Scholz

Reputation: 386540

You could take an object for keeping track of the indices for the keys and take a helper object for the reverted value/key relation.

const
    arraysObject = { "North American": ["CONUS", "NAMER", "CONUS/AK", "US-NC", "US-NE", "US-NW", "US-SC", "US-SE"], "Oconus": ["ALASKA", "GUAM", "HAWAII", "POLAR", "US-SAMOA"] },
    keys = Object.fromEntries(Object.entries(arraysObject).flatMap(([k, a]) => a.map(v => [v, k]))),
    EMPTY = Object.fromEntries(Object.keys(arraysObject).map(k => [k, ''])),
    listOfAreas = ["CONUS", "GUAM","US-SAMOA"],
    indices = {},
    result = [];

listOfAreas.forEach(value => {
    const key = keys[value];
    indices[key] ??= 0;
    (result[indices[key]++] ??= { ...EMPTY })[key] = value;
});

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Upvotes: 1

Related Questions