Friday, May 17, 2024
 Popular · Latest · Hot · Upcoming
125
rated 0 times [  131] [ 6]  / answers: 1 / hits: 64666  / 8 Years ago, sun, march 6, 2016, 12:00:00

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>

);

}
});

More From » reactjs

 Answers
50

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

[#63034] Thursday, March 3, 2016, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
ryderalfonsos

Total Points: 655
Total Questions: 88
Total Answers: 91

Location: Nauru
Member since Thu, Feb 2, 2023
1 Year ago
;