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

Finding the array index of an object with Javascript/React.js

本文关键字:对象 数组 索引 查找 js Javascript React 使用      更新时间:2023-09-26

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

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>
        );
    }
});

包装在可重用函数中的简单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');

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 版本(?)它在 flux 页面上的文档:

 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;
    },