How to set a Key name for each item in an initialized array

Viewed 78

I'm trying to initialize array accessRoleDisplay to unknown number of values and give each item in the array a key 'name' so I could use react table and add the value to the accessor

so it can look something like this

0: {name:xyz} 1: {name:xyz} 2: {name:xyz} . . . etc

This is my approach accessRoleDisplay:[{name:''}] but this just sets the first item to a name key and the remainder without. Any feedback is appreciated!

class MainCard extends Component {
    state = {
        accessRoleDisplay:[{name:''}],
    }

    handleChange = (tab) => {

        window.alert(`Tab changed to: ${tab}`);
    };

retrieveRoleAccess() {
    for (let i = 0; i < this.state.accessRoleData.length; i++) {
        for(let j=0; j<this.state.resourcesResponseData.length; j++) {
            if(this.state.accessRoleData[i].resource_id === this.state.resourcesResponseData[j].id)
            { 
                this.setState((prevState) => ({
                    accessRoleDisplay: [...prevState.accessRoleDisplay, this.state.resourcesResponseData[j].name]

                }));
               
            }
        }
    }
    console.log('this is role access display: ',this.state.accessRoleDisplay )
}
   
    async componentDidMount() {
     this.retrieveRoleAccess();
        ...
    }
    shouldComponentUpdate(nextProps, nextState) {
        return nextState !== this.state;
    }


    render() {


if (this.props.cardHandle) {
            return null
        }
        else {
            if (this.props.sendOptionSelected === 'Role') {
                
                return (
                    <Card mr={'0px'}>
                        <Tabs defaultActiveTab="Members" onChange={this.handleChange} >
                            {/* Group of tabs */}
                            <Tabs.Tab label="Members">Members</Tabs.Tab>
                            <Tabs.Tab label="Access">Access</Tabs.Tab>

                            {/* Tab panels */}
                            <Tabs.Panel label="Members">
                                <Table
                                    data={Array.isArray(this.state.outputRoleMembers) ? this.state.outputRoleMembers : [this.state.outputRoleMembers]}
           

                     defaultPageSize={[this.state.outputRoleMembers].length}
                                columns={
                                    [

                                        {
                                            Header: 'Fisrt Name',
                                            accessor: 'first_name'
                                        },
                                        {
                                            Header: 'Last Name',
                                            accessor: 'last_name'
                                        }

                                    ]
                                }
                                sortable={false}
                                resizable={false}
                                showPagination={false}
                                onSortedChange={() => { }}
                            />
                        </Tabs.Panel>
                        <Tabs.Panel label="Access">
                            <Table
                                data={Array.isArray(this.state.accessRoleDisplay) ? this.state.accessRoleDisplay : [this.state.accessRoleDisplay]}
                               
                                defaultPageSize={this.state.accessRoleDisplay.length}

                                columns={
                                    [
                                        {
                                            Header: 'Resource Name',
                                            //accessor: Need a key value here
                                        }
                                    ]
                                }
                                sortable={false}
                                resizable={false}
                                showPagination={false}
                                onSortedChange={() => { }}
                            />
                        </Tabs.Panel>
                    </Tabs>
                </Card>
            )
        }
}}}

const mapStateToProps = state => {
    return {
        roles: state.roles.item,
        users: state.users,
        permissions: state.permissions,
        resources: state.resources
    }
}
export default connect(mapStateToProps, { getComponentById, fetchComponent })(MainCard);
3 Answers

You can do this with a javascript Array:

accessRoleDisplay: Array(size).fill( {name: 'xyz'} ),

This will initialize an array of length size with the object {name: 'xyz'} at every index

according to documentation

accessor: String | Function

Required This string/function is used to build the data model for your column. The data returned by an accessor should be primitive and sortable. If a string is passed, the column's value will be looked up on the original row via that key, eg. If your column's accessor is firstName then its value would be read from row['firstName']. You can also specify deeply nested values with accessors like info.hobbies or even address[0].street If a function is passed, the column's value will be looked up on the original row using this accessor function, eg. If your column's accessor is row => row.name, then its value would be determined by passing the row to this function and using the resulting value.

Its accept both string or function but make sure you set the id, you can do any operation on the row like row.attrbuiteName === null ? "no thing" : row.attrbuiteName

{
     id:'name',
     Header: "Resource Name",
     accessor: row => row.attrbuiteName
     }

Iteration over given Array to make key value pair

var countries = ['Canada','Us','France','Italy'];
let obj = [];
for (var index in countries) {
    // don't actually do this
    obj.push({
        name: `name ${index}`,
        val: countries[index]
    });
}
obj.map((item) => item.name+ ' : ' + item.val); 

OutPut - Key:name value:val

0: "name 0 : Canada"

1: "name 1 : Us"

2: "name 2 : France"

3: "name 3 : Italy"

Related