Home > Software design >  Convert 2 Dimensional Array into Object
Convert 2 Dimensional Array into Object

Time:01-10

I'm hoping for some help converting a 2D array into an object.

In my spreadsheet I have a table of names and Google Drive folder identifiers (these are just examples, not real identifiers haha) -

Name Identifier
Name1 27uXqJux5ub4xlSOJpDgozuSBXpzdaqMbz
Name2 VDe67puraYNFyPNCptBkffuQcajjJLFzE

Using getvalues(), I have created an array of these cells called folderIds (leaving out the header row).

I then have another array which contains just the names, called names.

[Name1, Name2, Name3, etc]

My intention is to run a loop which uses the names in the second array to retrieve the folder identifier in the first array, but I'm stuck on how to convert folderIds into an object so that I can use the names array as a key to retrieve the folder identifier. The solution needs to be dynamic as folderIds will grow (and possibly change) over time, so I can't just manually define the object.

Ideally I would have an object that looks like this -

const folderIdsObj = {

    "Name1" : "27uXqJux5ub4xlSOJpDgozuSBXpzdaqMbz",
    "Name2" : "VDe67puraYNFyPNCptBkffuQcajjJLFzE"
    etc
}

And I would use folderIdsObj[names[i]] in a loop to retrieve the relevant folder identifier.

I've been digging around all over the internet, and it looks like the solution might be to use the map method, but I've never used map before and I'm not really sure where to start. I had a go but couldn't figure out how to map folderIds[0][0] to folderIds[0][1] (for example).

There may be a much simpler solution that I've missed too, though I've tried various array methods with no success.

Thanks in advance!

CodePudding user response:

you can achieve this by implementing this code...

twoDArray = [["Name1","12ee1du912nc1"], ["Name2", "1231cqnisani83"]]
    
const obj = Object.fromEntries(twoDArray.map(([k, v]) => [k, v]));
    
console.log(obj);

more information here

  • Related