我有一個數組,看起來像這樣:查找對象的數組索引使用Javascript/React.js
var skillsets = [
{id: 'one', name: 'george'},
{id: 'two', name: 'greg'},
{id: 'three', name: 'jason'},
{id: 'four', name: 'jane'},
];
什麼,我想要做的就是找到根據的形式給出一個值的行與JavaScript的id。例如,如果我將「id ='two'」放入函數中,我會將「1」作爲行返回。
我知道單行數組,skillsets.indexOf ['value']可以工作,但是這對於這個JSON集合不起作用。
我該如何做到這一點?
編輯:
Skills = React.createClass({
getInitialState: function() {
return { id: 'default' };
},
getIndex(value, arr, prop) {
for(var i = 0; i < arr.length; i++) {
if(arr[i][prop] === value) {
return i;
}
}
return -1; //to handle the case where the value doesn't exist
},
render: function() {
var index = getIndex(id, skillsets, 'id');
return (
<section id="three" className="main style1 special">
<div className="container">
<SkillsHeader skillsets={skillsets[index]}/>
{index}
<SkillsDetails details={details}/>
{index}
</div>
</section>
);
}
});
或者,如果找不到則返回-1,以匹配indexOf()的內容? – nnnnnn
是的,那會更好! –
說getIndex是未定義的 – user1072337