1

I want to loop an array to create an object.

input:

const input = [{email:email1, name: name1},{email:email2, name: name2}, {email:email3, name: name3}]

Desired output:

const output = {email1: name1, email2: name2, email3: name3
}

In javascript, I wrote

 let output = input.reduce((acc, cur, i) => {
                return (acc[cur.email] = cur.name)
            }, {})

But I got a typing error saying obj cannot have a string property. How should I type this function properly?

3
  • What is the full error? Commented Sep 18, 2019 at 20:30
  • in your first input, are emailX and nameX variables? If not then they are undefined when reading the value. Commented Sep 18, 2019 at 20:32
  • emailX, nameX represent string, not variables. Titian's answer solved the issue. Commented Sep 19, 2019 at 1:59

1 Answer 1

1

You need to be more explicit about the type of the result, typescript will not know that {} is supposed to be an object with any keys strings and string values:

const input = [{ email: 'email1', name: 'name1' }, { email: 'email2', name: 'name2' }, { email: 'email3', name: 'name3' }]
let output = input.reduce<Record<string, string>>((acc, cur, i) => {
    acc[cur.email] = cur.name
    return acc;
}, {})

Note: Also you need to return acc from the reducer function.

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

Comments

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.