Search code examples
jsonreactjsmap-functionprimereact

Dynamically generate list from json data in react


I am using primereact to generate table and i wanted to implement ColToggle Here is the link https://www.primefaces.org/primereact/#/datatable/coltoggle. Since I am dynamically generating columns from JSON Server , I want to dynamically generate this dropdown list for ColToggle implementation because i am taking api url from user input, to populate the dropdown:

let columns = [
            {field: 'vin', header: 'Vin'},
            {field: 'year', header: 'Year'},
            {field: 'brand', header: 'Brand'},
            {field: 'color', header: 'Color'}
        ]; 

and this is what i am trying to do:

fetch(this.state.apiURL)
            .then((response) => response.json())
            .then((findresponse) =>{
                this.setState({
                    columnSelector: findresponse.rootHeader
                });
                console.log(this.state.columnSelector);
                this.state.columnSelector.map((col) => {
                    return this.columns_multiselect = [{field: col.field, header: col.header}];
                })
                console.log(this.columns_multiselect);
            });

See the Map function in the code. JSON link: http://myjson.com/1620im.

This should be my output:

           [
                {field: 'vin', header: 'Vin'},
                {field: 'year', header: 'Year'},
                {field: 'brand', header: 'Brand'},
                {field: 'color', header: 'Color'}
            ]; 

How can i do this?


Solution

  • You may be looking for this,

    this.columns_multiselect = this.state.columnSelector.map(col => ({field: col.field, header: col.header}))