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

Finding an object in array and taking values from that to present in a select list

我有一个字符串值(例如 "Table 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"}]
 }
]

找到该对象后,我需要从列键中获取值并将它们显示在 select 列表中。

我知道如何进行第二部分,但首先是获取对象的访问权限,这让我遇到了麻烦。我正在尝试在 React 组件渲染中执行此操作。

如有任何帮助,我们将不胜感激。

感谢您的宝贵时间。

第一部分使用find方法:

function findArrayElementByTitle(array, title) {
  return array.find((element) => {
    return element.title === title;
  })
}

它将return条件element.title === title成立的第一个数组元素。

如果您需要从数组中获取具有 title: 'Table 1' 的所有项目,您可以使用 .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>

下面的方法将 return 所有具有特定值的元素(即在下面的情况下它是 isEdit:true)。

 filterArrayElementByEdit(array) {
    return array.filter((element) => {
      return element.isEdit === true;
    })
  }

下面的方法将 return 只有第一个元素。

 findArrayElementByEdit(array) {
    return array.find((element) => {
      return element.isEdit === true;
    })
  }