如何在React的前端更改JSON格式

时间:2019-05-29 06:42:46

标签: javascript json reactjs

我有fetch请求调用的JSON,如下所示:

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

我所做的是找到类型为1的对象,并将其添加到类型为2的对象中,并splice将我的数组添加到类型为2的对象中。现在看起来像这样:

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

我有两个问题。首先,我想向第二个数组的每个对象添加对象类型1,如下所示:

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

第二,我希望我的JSON仅包含Second数组,如下所示:

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

我该如何解决这两个问题?这是我的一部分代码:

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'))

1 个答案:

答案 0 :(得分:0)

您可以使用find从带有First的项目中获取type: 1。然后filtertype: 2项,并创建一个新的对象数组,其中First嵌套在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; }

您可以轻松获得第二个输出,例如output1[0].Second。取决于数组中有type: 2个项目。