0

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}), {});

1 Answer 1

3

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);

Sign up to request clarification or add additional context in comments.

2 Comments

I'm running into the following error with the assignment line: Element implicitly has an 'any' type because expression of type `Property${number}` can't be used to index type '{}'.
because you are using typescript, hence you need to define the types of parameters, replace (acc, value, index) with this (acc: {[key: string]: string}, value: string, index: number)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.