Object in function is undefined js

Viewed 73

I am trying to find out whether an object of my Object-Array CoilArray contains a certain value.

For this I am using the function hasValue

I want to be able to filter on two values and give back a filtered array, as you can see in the function filterArray

I have a problem in function hasValue.

The error message I am getting says:

obj is undefined

obj is obviously supposed to be the object that I am giving to the function.

Why is it undefined?
How can I define it?

hasValue itself seems to be working though

var CoilArray = [{
  id: "First Coil",
  systemId: ["System A", "System C"],
  fieldStr: ["Str A", "Str B"],
}, {
  id: "Second Coil",
  systemId: "System B",
  fieldStr: ["Str B", "Str C"],
}, {
  id: "Third Coil",
  systemId: "System C",
  fieldStr: "Str C",
}, ]

function hasValue(obj, key, value) {

  if (obj[key].indexOf(value) > -1) {
    return true;
  }
}

function filterArray(carray) {
  var arr = new Array();
  for (var i = 0; i <= carray.length; i++) {

    if (hasValue(carray[i], "systemId", "System A") &&
      hasValue(carray[i], "fieldStr", "Str B")) {

      arr.push(carray[i].id);
      console.log(carray[i].id);
    }
  }
  return arr;
}

hasValue(CoilArray[0], "fieldStr", "Str A");

filterArray(CoilArray);
2 Answers

Well you can trim all that down to this. And the check to see if the systemId is an array I referenced this answer

var filteredArray = CoilArray.filter(function (obj) {
  let isSystemA = false;
  let isStrB = false;

  // If Array then check if Array has value
  if (obj.systemId.constructor == Array) {
      isSystemA = obj.systemId.includes("System A") && isStrB;
  } else {
      isSystemA = obj.systemId === "System A";
  }

  if (obj.fieldStr.constructor == Array) {
      isStrB = obj.fieldStr.includes("Str B") && isStrB;
  } else {
      isStrB = obj.fieldStr === "Str B";
  }

  return isSystemA && isStrB;
});

This uses the filter function

Your for-loop runs from 0 to carray.length. As a consequence, the last time i is called, it has a value of carray.length. And carray[carray.length] doesn't exist.

Just stop looping at carray.length - 1 and your code works as expected.

Demo

var CoilArray = [{
  id: "First Coil",
  systemId: ["System A", "System C"],
  fieldStr: ["Str A", "Str B"],
}, {
  id: "Second Coil",
  systemId: "System B",
  fieldStr: ["Str B", "Str C"],
}, {
  id: "Third Coil",
  systemId: "System C",
  fieldStr: "Str C",
}, ]

function hasValue(obj, key, value) {
  if (obj[key].indexOf(value) > -1) {
    return true;
  }
}

function filterArray(carray) {
  var arr = new Array();
  for (var i = 0; i < carray.length; i++) {
    if (hasValue(carray[i], "systemId", "System A") && 
        hasValue(carray[i], "fieldStr", "Str B")) {
      arr.push(carray[i].id);
      console.log(carray[i].id);
    }
  }
  return arr;
}

hasValue(CoilArray[0], "fieldStr", "Str A");

filterArray(CoilArray);

Related