2016-10-03 5 views
0

ブラウザで出力された配列から{}を削除しようとしていますが、その方法はわかりません。私は配列がすでに正しく出力されていますが、正しいオブジェクトごとに新しい行に表示されますが、大括弧を削除したいと思います。JSON配列から角かっこを取り除いて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 

そして、それが可能であれば私も削除したいですスピーチマークが、括弧を削除するだけで今のところうまくいきます。

+0

あなたの出力は今のようにどのようになっていますか?あなたが理解しやすい画像またはビューを共有できる場合は、どうすればいいですか? –

+0

投稿を修正して、どのようにしたいですか見てください。 – DaveDavidson

答えて

2

あなたはおそらくそのようにすべきではありません。理由:

  1. それは、文字列(JSONに文字列化し、正規表現に置き換え)と

  2. 操作が高価である非自然な方法です。

代わりに、あなたのアレイの上にマッピングすることができます:

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

これは、ビューのHTML仕様の観点から、有効なものではなく、おそらくあなたのスタイリングを壊したかもしれないが、私はここにそれを残すことにしましたあなたはそれが有用であると考えるかもしれません。

0

これはあなたに役立つでしょう。ちょうど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)

関連する問題