Question

How is AngularJS able to reference an object in an array?

I've tried this:

SETUP:

var testarray = [];
var obj1 = {id:1};
var obj2 = {};
var obj3 = {};

testarray.push(obj1);
testarray.push(obj2);
testarray.push(obj3);

OPTION 1:

var refarr = testarray.filter(function(obj){
                        if(obj.id === 1){
                            return obj;
                        }
                        })[0];
console.log(testarray[0] === refarr); //RETURNS FALSE

OPTION 2

var refarr = testarray[0];
console.log(testarray[0] === refarr); //RETURNS FALSE

OPTION 3:

var refarr = {};
angular.copy(testarray[0], refarr);
console.log(testarray[0] === refarr); //RETURNS FALSE

How to solve this?

Was it helpful?

Solution

Your filter function is incorrect, it should be a predicate function, namely, it should return a boolean:

var refarr = testarray.filter(function(obj){
    return obj.id && obj.id === 1;
})[0];

console.log(testarray[0] === refarr); //YIELDS TRUE


var refarr = testarray[0];
console.log(testarray[0] === refarr); //YIELDS TRUE
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top