使用Javascript / React.js查找对象的数组索引

时间:2016-03-06 06:11:22

标签: javascript reactjs

我有一个看起来像这样的数组:

var skillsets = [
  {id: 'one', name: 'george'},
  {id: 'two', name: 'greg'},
  {id: 'three', name: 'jason'},
  {id: 'four', name: 'jane'},
];

我想要做的是根据使用Javascript以id形式给出的值来查找行。例如,如果我把" id ='两个'"进入这个功能,我喜欢" 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>

        );

    }
});

2 个答案:

答案 0 :(得分:9)

一个包含在可重用函数中的简单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是数组的每个可迭代的属性,应该与{ {1}}。

您可以将此功能用于任何具有您提到的结构的json。在您的具体情况下,请将其命名为:

value

答案 1 :(得分: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只支持lambda版本(?)它位于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;
    },