简体   繁体   中英

How to compare javascript objects of an array with other object

Bellow is polyline object

var firstpolyline = new L.Polyline(myPointList, {
    color: 'red',
    weight: 5,
    smoothFactor: 1
    });

I have added this polyline object into an array

var allpolylines = [];
allpolylines.push(firstpolyline);

Like this I have added more 5 polyline objects to this array.

Now I am creating one more polyline object.

var mytpolyline = new L.Polyline(myPointList, {
    color: 'red',
    weight: 5,
    smoothFactor: 1
    });

now I want to compare mytpolyline object with objects of an array & find index of that array object.

What I have tried is

var index = allpolylines.indexOf(mytpolyline);

but this is not giving index of array object.

You cannot compare Objects directly, they never are equal, except you are explicitely referencing them

var a = {};
var b = {};
var c = a;

b == a // false
c == a // true

If you want to check if objects in your array are equal, unfortunately you have to compare each property individually.

for (prop in a){
    if (a.hasOwnProperty){
        // compare a.prop to b.prop 
    }
}

With plain (non-object) properties and newer browser you could do this:

function comp(a,b){
    return Object.keys(a).every(function(prop){
        if (!b[prop]){ return false; }
        else if (a[prop] !== b[prop]){ return false; }
        return true;
    });
}

See an example .

References:

https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Object
https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/every

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