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>
);
}
});
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');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With