簡體   English   中英

從JSON數組React中刪除括號

[英]Remove brackets from JSON array React

我正在嘗試從瀏覽器中的輸出數組中刪除} {括號,以使其在頁面上看起來更干凈,但是我不確定如何這樣做。 我已經正確輸出了數組,在每個對象的新行上是正確的,但是我想刪除括號。

import React, { Component } from 'react';
import './App.css';
import $ from 'jquery';
import { Image } from 'react-native';

class App extends Component {

  state = {result : null}

  componentDidMount = () => {

    $.ajax({
      type: "GET",
      url: 'http://localhost:3001/data',
      data: {},
      xhrFields: {
        withCredentials: false
      },
      crossDomain: true,
      dataType: 'JSON',
      success: (result) => {
        this.setState({result : result});
      }
    });

  };

  render() {
    return (
          <div className="App">
            <header>
              <Image
              style={{width: 200, height: 50, margin: 'auto'}}
              source={require('./img/XXX.png')}
              />
            </header>
            <div className='renderhere'>
              <pre>{JSON.stringify(this.state.result, null, 2).replace(/]|[[]/g, '')}</pre>
            </div>
            <footer>Last Application Deployment v1.0. By XXX.</footer>
          </div>

        );
  }
    }

export default App;

當前的輸出如下所示:

  {
    "appName": "App 1",
    "latestDeploymentDate": 0
  },
  {
    "appName": "App 2",
    "latestDeploymentDate": 1
  },
  {
    "appName": "App 3",
    "latestDeploymentDate": 2
  },
  {
    "App 4",
    "latestDeploymentDate": 3
  },
  {
    "appName": "App 5",
    "latestDeploymentDate": 4
  }

但是我希望輸出看起來像這樣:

    "appName": "App 1",
    "latestDeploymentDate": 0

    "appName": "App 2",
    "latestDeploymentDate": 1

    "appName": "App 3",
    "latestDeploymentDate": 2

    "appName": "App 4",
    "latestDeploymentDate": 3

    "appName": "App 5",
    "latestDeploymentDate": 4

而且,如果有可能,我也想刪除語音標記,但是現在就刪除括號就可以了。

您可能不應該那樣做。 原因:

  1. 這是非自然的方式

  2. 使用字符串(字符串化為json並用正則表達式替換)的操作非常昂貴。

相反,您可以映射數組:

<pre>
  {this.state.result.map(item => {
    return (
      <span>"appName": "{item.appName}"</span>
      <span>"latestDeploymentDate": "{item.latestDeploymentDate}"</span>
    )
  })
</pre>

從HTML規范的角度來看,這不是有效的方法,並且可能會破壞您的樣式,但是出於您可能認為有用的情況,我決定將其保留在此處。

這應該對您有幫助。 只是做一個regex替換!

 var arr = [{ "appName": "App 1", "latestDeploymentDate": 0 }, { "appName": "App 2", "latestDeploymentDate": 1 }, { "appName": "App 3", "latestDeploymentDate": 2 }, { "appName": "App 4", "latestDeploymentDate": 3 }, { "appName": "App 5", "latestDeploymentDate": 4 }] var str = JSON.stringify(arr) var final = str.replace(/{|},|}/g, "\\n").replace(/\\[|\\]|"/g, "").replace(/,/g, ',\\n') console.log(final) 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM