简体   繁体   中英

Javascript process keys in Array of objects

Iam using this library to track some colors on video streamed by my webcam.

Simply the code to return tracked objects is as simple as :

tracker.on('track', function(event) {

        console.log(event.data)

                  });

the event.data is an array of objects , each object contains 5 keys 'color' , 'x' , 'y' , 'height' , 'width' , what im trying to do is to find 2 objects which their 'Xs' has difference of 10 ie x1-x2=10 , or x2-x1=10 ( lets call them adjacent objects ) , known that the event.data changes with real time tracking , this is not a static array.

Tried using jQuery .grep() , but cant figure out how to process more than item.

You'll just need to loop through the array and compare those values:

for var i = 0; i < event.data.length; i++ )
{
    var data1 = event.data[ i ];

    //Now we'll loop through the whole array to compare
    for ( var x = 0; x < event.data.length; x++ )
    {
        if ( Math.abs( data1.x - event.data[ x ].x ) === 10 )
        {
            return { x1: data1, x2: event.data[ x ] };
        }
    }
}

I suggest creating another container array to contain (really?) all the arrays produced by the tracker:

var container = [];
tracker.on("track", function(event) {
    var newIndex = container.length;
    container[newIndex] = event.data;
    process(newIndex);
});

Now you have all the data saved, you can process it:

function process(index) {
    var adjacent = [];
    for(var i = 0; i < container.length; i++) {
        var subtract = container[index].x - container[i].x;
        if(subtract == 10 || subtract == -10)
          adjacent.push(i);
    }
    return adjacent;
}

So now, if process() returns true, you know the difference is 10. What you do with that now is up to you.

Here's how I would have done it ( Array.prototype.filter and $.grep() does the same thing):

var events = [];
tracker.on('track', function(e){
    events.push(e.data);
});

function getEventsByXDiff(x){
    return events.filter(function(e){
        return e.x - x === 10 || x - e.x === 10
    });
}

// Usage: getEventsByXDiff(someEvent.x);

Example with dummy event data: http://jsfiddle.net/11mvLtqp/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM