LOL. NO.
LOL. NO.

Reputation: 657

Converting a dynamic string array to an object with keys

I have the following string array:

let arrayExample = ['', 'test1', 'test2', '', 'test3', 'test1', ''];

This is also dynamic, so the size can change at any given time. I would like to be able to convert this to an object that looks like the following:

{
    Property0: '',
    Property1: 'test1',
    Property2: 'test2',
    Property3: '',
    Property4: 'test3',
    Property5: 'test1',
    Property6: ''
}

Is there a way to dynamically declare the keys/property names? I've tried the following, but this seems to assign keys as numerical values and I'm not able to access them:

newArrayExample = Object.assign({}, arrayExample);
console.log(newArrayExample);
// { 0: '', 1: 'test1', 2: 'test2', 3: '', 4: 'test3', 5: 'test1', 6: '' }

I've also tried using reduce(), but that seems to only bring back unique values and I need to preserve those values unless if I'm using it wrong:

newArrayExample = arrayExample.reduce((a, v) => ({ ...a, [v]: v}), {});

Upvotes: 0

Views: 37

Answers (1)

MHD Alaa Alhaj
MHD Alaa Alhaj

Reputation: 3223

The best way is by using reduce() method, but you are using it wrong.

Since the property name is set to the value of the array element itself [v] you'll encounter two main issues:

1. Duplicate Values: If the array contains duplicate values (like test1 appears twice in your example), using the value as a key will overwrite the previous property with the same key. Therefore, you will lose some data in the final object.

2. Empty Strings as Keys: If the array contains empty strings (like in your example), the property key will be an empty string, which is generally not desirable.

let arrayExample = ['', 'test1', 'test2', '', 'test3', 'test1', ''];

let result = arrayExample.reduce((acc, value, index) => {
  acc[`Property${index}`] = value;
  return acc;
}, {});

console.log(result);

Upvotes: 3

Related Questions