我有一个字符串值(例如“表1”),我需要使用它在数组中查找特定对象,如下所示:
[
{
lookups: [],
rows: [{data: {a: 1, b: 2}}, {data: {a: 3, b: 4}}],
title: "Table 1",
columns: [{name: "a"}, {name: "b"}]
},
{
lookups: [],
rows: [{data: {c: 5, d: 6}}, {data: {c: 7, d: 8}}],
title: "Table 2",
columns: [{name: "c"}, {name: "d"}]
}
]
找到该对象后,我需要从columns键中获取值并将它们显示在选择列表中。
我知道如何做第二部分,但是首先是要访问我遇到麻烦的对象。我正在尝试在React组件渲染中执行此操作。
任何帮助,将不胜感激。
谢谢你的时间。
如果需要从数组中获取所有具有的项目title: 'Table 1'
,则可以使用()。如果只需要第一个项目,则可以使用()。.filter
Example
title: 'Table 1'
.find
Example
var App = React.createClass({
columns: function(condition) {
return this.props.data
.filter((e) => e.title === condition)
.map(e => e.columns)
.reduce((prev, current) => prev.concat(current), [])
.map((column, index) => <p key={ index }>{ column.name }</p>)
},
render: function() {
const condition = 'Table 1';
return <div>{ this.columns( condition ) }</div>;
}
});
const data = [{
lookups: [],
rows: [{data: {a: 1, b: 2}}, {data: {a: 3, b: 4}}],
title: "Table 1",
columns: [{name: "a"}, {name: "b"}]
}, {
lookups: [],
rows: [{data: {c: 5, d: 6}}, {data: {c: 7, d: 8}}],
title: "Table 2",
columns: [{name: "c"}, {name: "d"}]
}, {
lookups: [],
rows: [],
title: "Table 1",
columns: [{name: "m"}, {name: "n"}]
}];
ReactDOM.render(
<App data={ data } />,
document.getElementById('container')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="container"></div>
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句