2016-09-01 45 views
1

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

一旦我找到了對象,我需要從列鍵中取值並將它們顯示在選擇列表中。

我知道如何做第二部分,但它首先獲得對象的訪問權限,我遇到了麻煩。我正在嘗試在React組件呈現中執行此操作。

任何幫助,這將不勝感激。

謝謝你的時間。

+0

所以你的問題是在數組中找到對象,其中key = value,對吧?!我會用下劃線_.findWhere或lodash –

回答

3

如果你需要得到陣列具有title: 'Table 1'所有項目,您可以使用.filterExample,如果你只需要第一個項目,其中title: 'Table 1'你可以使用.findExample

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>

+1

完美的謝謝! – BeeNag

2

在第一部分使用find方法:

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

它將返回的量,條件element.title === title成立第一個數組元素。

相關問題