【问题标题】:How to get the indices of the objects in this array / JS如何获取此数组/JS中对象的索引
【发布时间】:2014-11-30 13:14:28
【问题描述】:

如果我有一个对象数组:

myArray[person{}, person{}, person{}]

每个人都可以包含一组 Children 对象,如下所示:

person{
    name: 'XXX',
    age: 'XXX',
    children: [{
        name: 'XXX',
        age: 'XXX'
    },{
        name: 'XXX',
        age: 'XXX'
    },{
        name: 'XXX',
        age: 'XXX'
    }]
}

如何获取 myArray 中每个 Person 的索引以及 Children 数组中对象的索引?

我正在使用 indexOf() 像这样在 myArray 中获取 Person 对象的索引,它正在工作:

function getObjectIndex(myObject) {                     
    var myArray = _.flatten(_.values(objects));

    var ret = myArray.indexOf(myObject); 

    return ret; //RETURNS 0, 1, 2 etc...
}

我不确定如何扩展 getObjectIndex 的功能以获取每个 Person 中的 Children 对象的索引

function getObjectIndex(myObject) {                     
    var myArray = _.flatten(_.values(objects));

    var ret = myArray.indexOf(myObject); 

    if (myObject.children.length > 0){

        //UNSURE WHAT LOGIC TO APPLY HERE

        ret += ;
    }

    return ret;
}

如果存在任何子对象,我希望 getObjectIndex 返回:

Person index in myArray _ Children index in Person

所以如果一个 Person 中有三个 Children 对象:

0_0
0_1
0_2

非常感谢任何帮助或建议。

【问题讨论】:

    标签: javascript arrays underscore.js indices


    【解决方案1】:

    如果将数组传递给map,那么迭代器函数的第二个参数就是对象的索引。这可以用来得到你想要的结果:

        var indexArrays = _.map(myArray, function(person, personIndex){
            return _.map(person.children, function(child, childIndex){
                return personIndex + '_' + childIndex;
            });
    
        });
    
        var indices = _.flatten(indexArrays);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-10-23
      • 1970-01-01
      • 2012-02-21
      • 2018-04-25
      • 2021-02-09
      • 2020-05-04
      • 2017-06-16
      • 2014-05-14
      相关资源
      最近更新 更多