使用 Javascript/React.js 查找对象的数组索引
Finding the array index of an object with Javascript/React.js
我有一个看起来像这样的数组:
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;
},
相关文章:
- Javascript(Angular)从一个对象数组到第二个数组查找值
- 在Javascript中转换对象数组
- 在JavaScript中通过索引从对象数组中获取值
- Backbone虹吸以获取对象数组
- 如何在DataTables 2.1中迭代对象数组
- Javascript-根据赋值顺序,按键合并对象数组
- 将事件附加到对象/数组
- jQuery$.inArray()总是返回-1和一个对象数组
- javascript处理一个对象数组以获得一个新的对象数组
- javascript在数组中获取对象数组中键的所有不同值
- 在对象数组中查找多个值的d3范围
- Undercore.js获取对象数组中键对象的值
- 在mongoose中使用正则表达式在对象数组中进行查询搜索
- 如何通过json对象数组为嵌套对象赋值
- 如何循环通过2个对象数组并通过匹配id进行合并
- 为对象数组创建列表项
- 如何使用javascript合并两个对象数组
- JSON到对象数组,并向每个对象添加项
- JavaScript:从对象数组中获取唯一值及其计数
- 按不同项目对对象数组进行排序