简体   繁体   English

反应中嵌套对象的唯一键

[英]Unique Key for nested objects in react

I have following structure for JSON data structure我对 JSON 数据结构有以下结构

[
 [
  { city: x
    patients: x
    id: 1
  },
  { city: y
    patients: y 
    id: 2  
}
],

 [
  { city: x
    patients: x
    id: 1
  },
  { city: y
    patients: y 
    id: 2  
}
 ] 
]

Is this optimal data structure for my data, where each nested sub array represents a day, the nested objects are cities and the id are unique key for each city.这是我的数据的最佳数据结构吗,其中每个嵌套子数组代表一天,嵌套对象是城市,id 是每个城市的唯一键。

The best thing is that each object has a unique id, but if you don't have one, you can use the index of map method:最好的是每个 object 都有一个唯一的 id,但是如果没有,可以使用 map 的索引方法:

objects.map((el, idx) => { 
    ....
    // you can use idx as unique index
    ....
}) 

For nested objects you can compose the idx (for example "idxmain_idxsub")对于嵌套对象,您可以编写 idx(例如“idxmain_idxsub”)

One way you could go about this is by combining both the index and city for each object and create a unique identifier.您可以 go 关于此的一种方法是结合每个 object 的indexcity并创建一个唯一标识符。

 const data = [ [ { id: 1, city: "New York", patients: 100 }, { id: 2, city: "Boston", patients: 50 }, ], [ { id: 1, city: "New York", patients: 120 }, { id: 2, city: "Boston", patients: 75 }, ] ]; function App() { return ( <div> {data.map((items, idx) => ( <ul key={idx}> {items.map((item) => ( <li key={`${idx}-${item.id}`}> [{idx}-{item.id}] {item.city}: {item.patients} </li> ))} </ul> ))} </div> ); } ReactDOM.render( <App />, document.getElementById("app") );
 <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script> <div id="app"></div>

Or, if you want to just flatten your array and have all object within a single array, you could do something similar like I did above:或者,如果您只想展平您的阵列并将所有 object 放在一个阵列中,您可以像我上面那样做类似的事情:

 const data = [ [ { id: 1, city: "New York", patients: 100 }, { id: 2, city: "Boston", patients: 50 }, ], [ { id: 1, city: "New York", patients: 120 }, { id: 2, city: "Boston", patients: 75 }, ] ]; const flattened = data.reduce( (accumulator, items, idx) => { const cities = items.map((city) => { return { uniqId: `${idx}-${city.id}`, ...city }; }) return [...accumulator, ...cities ]; }, [] ) console.log(flattened)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM