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

喜夏-厌秋 提交于 2019-12-09 02:36:50

问题


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"}]
 }
]

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

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.

Thanks for your time.


回答1:


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>



回答2:


For the first part use find method:

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

It will return the first array element for which the condition element.title === title holds true.



来源:https://stackoverflow.com/questions/39270107/finding-an-object-in-array-and-taking-values-from-that-to-present-in-a-select-li

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!