Create objects with map function, currentValue as a object key

Tags: ,



In my ReactApp, I keep in state list of users (fetched from backend API). It is called “currentUsers”.

class Lobby extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            currentUsers: ["TestUser1", "TestUser2"],
            buttonList: [],
        }
    }

I would like to populate buttonList to have array of object where array will look like this(example):

[{
"TestUser1": {
    "inviteButtonValue": "Invite",
    "chatButtonValue": "Chat"
          }
},
{"TestUser2": {
    "inviteButtonValue": "Invite",
    "chatButtonValue": "Chat"
          }
}]

There is my main function.

    produceButtonValues = (currentUsersList) => {
        let inputList = currentUsersList
            .map( (nickname) => {
                    return {
                        nickname: {
                            "inviteButtonValue": "Invite",
                            "chatButtonValue": "Chat"
                        }
                    };
                }
            );
        this.setState({buttonList: inputList});
    }

I tried to use map but it looks like I cannot get array element as object key, i.e. “TestUser1” etc. but got “nickname” instead (seen in “Components” tab in Firefox DevTools Add-on)

...
{nickname: {
    "inviteButtonValue": "Invite",
    "chatButtonValue": "Chat"
          }
}
...

I trigger my function as below:

    componentDidMount() {
        this.produceButtonValues(this.state.currentUsers);

How to solve it? By the way: when I run console.log(this.state.buttonList); just after setState, I still see empty array as it was made in initial state. Why?

Answer

It’s called Property accessors

You use it like this:

currentUsersList.map(nickname => ({
    [nickname]: {
       inviteButtonValue: Invite,
       chatButtonValue: Chat
    }
});

Property Accessors
Computed property names



Source: stackoverflow