Search code examples
javascriptarraysunderscore.jsindices

How to get the indices of the objects in this array / JS


If I have an array of objects:

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

And each person can contain an array of Children objects like this:

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

How can I get the index of each Person in myArray and also the index of the objects in the Children array?

I'm getting the index of the Person objects in myArray like this, using indexOf(), which is working:

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

    var ret = myArray.indexOf(myObject); 

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

I'm unsure how to expand the functionality of getObjectIndex to get the indices of the Children objects in each Person

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;
}

If there are any children objects present, I ideally would like getObjectIndex to return:

Person index in myArray _ Children index in Person

So if there are three Children object in a Person:

0_0
0_1
0_2

Any help or suggestions would be very much appreciated.


Solution

  • If you pass an array to map then the second parameter to the iterator function is the index of the object. This can be used to get the result you want:

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