首页 > 解决方案 > How to display an array of pair arrays as key values pairs?

问题描述

I am writing a client in Ract that receives streaming data representing objects from a back end. The client parses this data and dynamically builds the object as a javascript data structure (typically an object or an array). The backend has a Timeseries datatype that consists of timestamp keys and arbitrary values. A Timeseries can have duplicate timestamp keys like so:

{
 '2019-08-22T18:34:15.777927965Z' : 1,
 '2019-08-22T18:34:15.777927965Z' : 2,
 '2019-08-22T18:34:15.777927965Z' : 3,
}

This means that I cannot use a javascript object to build this datastructure in the client given that only the last key/value pair added will be stored since the keys are the same.

My solution was to collect this data in an array:

[
    ['2019-08-22T18:34:15.777927965Z', 1],
    ['2019-08-22T18:34:15.777927965Z', 2],
    ['2019-08-22T18:34:15.777927965Z', 3],
]

The problem is that I have been asked to display this data in key/value format the way a javascript object would be displayed. I am using the react-json-tree npm package to dislpay all the objects I am constructing which just takes an object or array and formats it nicely with collapsable dropdown arrows in the UI (this is not essential). What options do I have to turn my array of arrays in the code into a nicely formatted object like data structure in the UI?

TLDR: How do I display an array like this:

[
    ['2019-08-22T18:34:15.777927965Z', 1],
    ['2019-08-22T18:34:15.777927965Z', 2],
    ['2019-08-22T18:34:15.777927965Z', 3],
]

As colon separated key/value pairs in the UI, like objects? Ideally I could pass this data structure into a library like react-json-tree.

标签: javascriptarraysreactjs

解决方案


You can display your data in the following way, if you want them to be given as a list :

const data = [
    ['2019-08-22T18:34:15.777927965Z', 1],
    ['2019-08-22T18:34:15.777927965Z', 2],
    ['2019-08-22T18:34:15.777927965Z', 3],
]
 
 const Renderer = () =>
  <ul>
    {data.map(([key, val], id) => <li key={id}>{key}; {val}</li>)}
  </ul>;
 
ReactDOM.render(<Renderer/>, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.0/umd/react-dom.production.min.js"></script>
<div id="root"/>

To display it using react-json-tree, how about wrapping your array within an object ?

const data = [
    ['2019-08-22T18:34:15.777927965Z', 1],
    ['2019-08-22T18:34:15.777927965Z', 2],
    ['2019-08-22T18:34:15.777927965Z', 3],
]

<JSONTree data={{log: data}} />

OR

const data = {
  log : [
    ['2019-08-22T18:34:15.777927965Z', 1],
    ['2019-08-22T18:34:15.777927965Z', 2],
    ['2019-08-22T18:34:15.777927965Z', 3],
  ]
}

<JSONTree data={log} />

推荐阅读