2016-03-06 37 views
4

我有一個數組,看起來像這樣:查找對象的數組索引使用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> 

     ); 

    } 
}); 

回答

5

簡單for環包裹在一個可重複使用的功能是不夠好:

function 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 
} 

這裏,value是要匹配的值,arr是對象數組,而prop是該數組的每個迭代的屬性應與value相匹配。

你可以使用這個函數用於你提到的結構的任何json。在你的具體情況下,你可以這樣稱呼它:

var index = getIndex('one', skillsets, 'id'); 
+0

或者,如果找不到則返回-1,以匹配indexOf()的內容? – nnnnnn

+0

是的,那會更好! –

+0

說getIndex是未定義的 – user1072337

3

Lodash有findIndex方法正是這樣做的。

var users = [ 
    { 'user': 'barney', 'active': false }, 
    { 'user': 'fred', 'active': false }, 
    { 'user': 'pebbles', 'active': true } 
]; 

_.findIndex(users, function(o) { return o.user == 'barney'; }); 
// → 0 

// The `_.matches` iteratee shorthand. 
_.findIndex(users, { 'user': 'fred', 'active': false }); 
// → 1 

// The `_.matchesProperty` iteratee shorthand. 
_.findIndex(users, ['active', false]); 
// → 0 

// The `_.property` iteratee shorthand. 
_.findIndex(users, 'active'); 
// → 2 

但我認爲ES6只支持拉姆達版本反正它在文檔上the flux page(?):

removeTodo (id) { 
     let index = this.todos.findIndex(todo => todo.get('id') === id); 

     // remove the todo with the ID of id, but only if we have it to begin with 
     this.todos = index > -1 ? 
      this.todos.remove(index) : 
      this.todos; 
    },