Finding an index of an object array using Javascript / React.js

I have an array that looks like this:

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

what I would like to do is find a string based on the value given in id form with Javascript. For example, if I put "id =" two "in a function, I would like for" 1 "to be returned as a string.

I know that for a single-row array, skillsets.indexOf ['value'] will work, but it will not work for this set of JSON.

How can i achieve this?

EDIT:

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>

        );

    }
});
+4
source share
2 answers

A simple loop forenclosed in a reusable function is good enough:

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');
+5

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 - (?) :

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

All Articles