函数返回一个对象的索引深深嵌套数组 [英] function to return index of an object in a deeply nested array

查看:176
本文介绍了函数返回一个对象的索引深深嵌套数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要写也许,仅仅输出对象的索引数组里面,很明显,使用$ .inArray返回此只需在下面的例子中精细的功能。

I need to perhaps write a function that just outputs the index of an object inside an array, obviously, using $.inArray returns this just fine in the example below.

array = ['one', 'two', 'three'];

$.inArray('one', array) // 0

通过更精细的阵列,如何可以找到嵌套的对象的索引?

With a more elaborate array, How can I find the index of the objects nested within?

array = [
    {
        name: 'One', // index??
        data: {
            title: 'Title One',
            content: 'Content One'
        }
    },
    {
        name: 'Two',
        data: {
            title: 'Title Two',
            content: 'Content Two'
        }
    },
    {
        name: 'Three',
        data: {
            title: 'Title Three',
            content: 'Content Three'
        }
    }
];

我听说$ .grep()方法,的indexOf()..不知道要使用哪一个只返回对象是

I've heard of the $.grep() method, indexOf() .. not sure which one to use to just return an integer of the index the object is in

推荐答案

您不需要pre-写功能,只需遍历阵列和比较名称属性:

You don't need a pre-written function, just iterate over your array and compare the name property:

function findValue(array, nameWeAreLookingFor) {
    for(var i = 0; i<array.length; i++) {
        if(array[i].name === nameWeAreLookingFor) return i;
    }
    return -1;
}

这篇关于函数返回一个对象的索引深深嵌套数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆