从JSON数组中删除括号React

时间:2016-10-03 12:37:18

标签: javascript arrays json reactjs

我正在尝试从浏览器中输出的数组中删除} {括号,以使其在我的页面上看起来更干净,但我不确定如何这样做。我已经正确地输出了数组,在每个对象的新行上是正确的,但我想删除括号。

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

如果有可能我也想删除语音标记,但现在只需删除括号即可。

2 个答案:

答案 0 :(得分:2)

你不应该这样做。原因:

  1. 这是非常自然的方式

  2. 使用字符串进行操作(字符串化为json并替换为regexp)非常昂贵。

  3. 相反,您可以映射数组:

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

    从HTML规范的角度来看,这不是有效的,可能会破坏你的造型,但我决定把它留在这里,你认为它有用。

答案 1 :(得分:0)

这应该对你有所帮助。只需做一个regex替换!

&#13;
&#13;
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)
&#13;
&#13;
&#13;