在两个数组上反应映射并在表中显示结果

时间:2018-11-29 11:59:56

标签: javascript reactjs

我有两个数组:

ID  Date    SessionID   discount    price
13  2015-12-07  20      no          15.99
13  2015-12-07  30      yes         12.99

如何映射两个数组并在表中设置数据,如下所示:

this.state = {
  array1: [{id: 1, name: 'test1'}, {id: 2, name: 'test2'}],
  array2: [{testId: 1, color: 'red'}, {testId: 1, color: 'blue'}, {testId:2, color: 'green'}]
}
第二个数组的

test1 red blue test2 green 与第一个数组的ID相同。

1 个答案:

答案 0 :(得分:1)

您可以使用filtertestId中查找与id中元素array1具有相同class App extends React.Component { state = { array1: [{ id: 1, name: "test1" }, { id: 2, name: "test2" }], array2: [ { testId: 1, color: "red" }, { testId: 1, color: "blue" }, { testId: 2, color: "green" } ] }; render() { const { array1, array2 } = this.state; return ( <div> {array1.map(el => { const colors = array2.filter(e => e.testId === el.id); return ( <div key={el.id}> <span>{el.name}</span> {colors.map((c, i) => ( <span key={i}> {c.color} </span> ))} </div> ); })} </div> ); } } ReactDOM.render(<App />, document.getElementById("root"));的所有元素,并进行渲染。

示例

<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="root"></div>
select Name
from Customers
where Name like N'%özgür%'