简体   繁体   中英

How to change the format of JSON in the front-end in React

I have JSON called by fetch request that looks like this:

[{
    "type": "1",
    "First": {
      "Id": "123456"
    }
  },
  {
    "type": "2",
    "Second": [{
        "Id": "13333"
      },
      {
        "Id": "255555"
      },
      {
        "Id": "37777"
      },
      {
        "Id": "48888"
      }
    ]
  }
]

What I did is that I find object with type 1 and add it to object which type 2 and splice my array to just have an object which type 2. Now it looks like this:

[{
  "type": "2",
  "First": {
    "Id": "123456"
  },
  "Second": [{
      "Id": "13333"
    },
    {
      "Id": "255555"
    },
    {
      "Id": "37777"
    },
    {
      "Id": "48888"
    }
  ]
}]

I have two problems. First I want to add obeject type 1 to every objects of array second, like this:

[{
  "type": "2",
  "Second": [{
      "Id": "13333",
      "First": {
        "Id": "123456"
      }
    },
    {
      "Id": "255555",
      "First": {
        "Id": "123456"
      }
    },
    {
      "Id": "37777",
      "First": {
        "Id": "123456"
      }
    },
    {
      "Id": "48888",
      "First": {
        "Id": "123456"
      }
    }
  ]
}]

Secondly I want my JSON to just included Second array, like this:

[{
    "Id": "13333",
    "First": {
      "Id": "123456"
    }
  },
  {
    "Id": "255555",
    "First": {
      "Id": "123456"
    }
  },
  {
    "Id": "37777",
    "First": {
      "Id": "123456"
    }
  },
  {
    "Id": "48888",
    "First": {
      "Id": "123456"
    }
  }
]

How can I solve these two issues? Here is a piece of my code:

class App extends React.Component {
constructor(props) {
    super(props);
    this.state = {
        data: [],
        library: null,
        perPage: 20,
        currentPage: 1,
        maxPage: null,

    }
}
componentDidMount() {
    fetch('/json.bc', {
        method: 'get',
    })
        .then(response => response.text())
        .then(text => {
            const Maindata = JSON.parse(text.replace(/\'/g, '"'))
            const type1 = Maindata.find(({ type }) => type === '1');
            const MergedData = Maindata.map(item => item.type === '1' ? item : { ...type1, ...item });
            const MergedData2 = MergedData.splice(1)

            this.setState(state => ({
                ...state,
                data: MergedData2
            }), () => {
                this.reorganiseLibrary()
            })
        }).catch(error => console.error(error))

}

reorganiseLibrary = () => {
    const { perPage, data } = this.state;
    let library = data;
    library = _.chunk(library, perPage);
    this.setState({
        library,
        currentPage: 1,
        maxPage: library.length === 0 ? 1 : library.length
    })
}


previousPage = event => {
    this.setState({
        currentPage: this.state.currentPage - 1
    })
}

nextPage = event => {
    this.setState({
        currentPage: this.state.currentPage + 1
    })
}


handlePerPage = (evt) =>
    this.setState({
        perPage: evt.target.value
    }, () => this.reorganiseLibrary());


renderLibrary = () => {
    const { library, currentPage } = this.state;
    if (!library || (library && library.length === 0)) {
        return <div>NOResult</div>
    }
    return library[currentPage - 1].map((item, i) => (
        <div className="Wrapper">{item.id}</div>
    ))
}


render() {
    const { library, currentPage, perPage, maxPage } = this.state;
    return (
        <div>
            {this.renderLibrary()}
            <ul id="page-numbers">
                <li>
                    {currentPage !== 1 && (
                        <button onClick={this.previousPage}></button>
                    )}
                </li>
                <li>{this.state.currentPage}</li>
                <li>{this.state.maxPage}</li>
                <li>
                    {(currentPage < maxPage) && (
                        <button onClick={this.nextPage}></button>
                    )}
                </li>
            </ul>
        </div>
    )
}
}
ReactDOM.render(<App />, document.getElementById('Result'))

You could get the First from an item with type: 1 using find . Then filter the type: 2 items and create an new array of objects with First nested in every object in Second

 const input=[{"type":"1","First":{"Id":"123456"}},{"type":"2","Second":[{"Id":"13333"},{"Id":"255555"},{"Id":"37777"},{"Id":"48888"}]}] const { First } = input.find(a => a.type === "1") || {} const output1 = input.filter(a => a.type === "2") .map(a => { const Second = a.Second.map(b => ({ ...b, First })) return { ...a, Second } }) console.log(JSON.stringify(output1, null, 3)) 
 .as-console-wrapper { max-height: 100% !important; top: 0; } 

You can easily get the second output like output1[0].Second . Depends on how many items with type: 2 will be there in the array.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM