Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I have an array that looks like so:

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 the row based on a value given in the form of an id with Javascript. For instance, if I put "id='two'" into the function, I'd like "1" to be returned as the row.

I know for a single row array, skillsets.indexOf['value'] would work, but that won't work for this JSON set.

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>

        );

    }
});
like image 236
user1072337 Avatar asked Mar 06 '16 06:03

user1072337


1 Answers

A simple for loop wrapped 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
}

Here, value is the value you want to match against, arr is the array of objects, and prop is the property of each iterable of the array which should match the value.

You can use this function for any json with the structure you mentioned. In your specific case, call it like this:

var index = getIndex('one', skillsets, 'id');
like image 91
Tarun Dugar Avatar answered Oct 10 '22 23:10

Tarun Dugar