在数组中查找对象并从中获取值以显示在选择列表中

问题描述:

我有一个字符串值(例如表1"),我需要用它来查找数组中的特定对象,如下所示:

I have a string value (e.g. "Table 1") that I need to use to find a specific object in an array that looks like so:

[
 {
  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键中获取值并将它们显示在选择列表中.

Once I have found that object I then need to take the values from the columns key and display them in a select list.

我知道如何做第二部分,但是首先是要访问我遇到麻烦的对象.我正在尝试在React组件渲染中执行此操作.

I know how to do the second part, but it is getting access to the object in the first place that I am having trouble with. I am trying to do this within a React component render.

任何帮助,将不胜感激.

Any help with this would be greatly appreciated.

感谢您的时间.

如果需要从具有title: 'Table 1'的数组中获取所有项目,则可以使用 Example ).如果只需要title: 'Table 1'的第一项,则可以使用 Example )

If you need to get all items from array which have title: 'Table 1', you can use .filter(Example)., if you need only first item where title: 'Table 1' you can use .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>