0

I have array of object

var myarray = 
[
  {
    "ID":100, 
    "Nama":"IPAddress",    
    "AData":"192.168.11.10"
  },{
    "ID":101, 
    "Nama":"Frekuensi", 
    "AData":"5.X Ghz"
  },{
    "ID":102, 
    "Nama":"Type", 
    "AData":"Access Point"
  }
]

I create function search array like this base on "ID" like this

function SearchArrayBasedID(NamaArray, SValue, ReturnKey){
    var index1 = -1;
    for (var i = 0; i < NamaArray.length; i++) {
        if (NamaArray[i].ID == SValue){
            index1 = i
            i = NamaArray.length;
        } 
    }
    var ReturnValue;
    if (ReturnKey == 0){
        ReturnValue = index1
    }else{
        ReturnValue = NamaArray[index1].ReturnKey;
    }
    return ReturnValue

}

And it's success. But If I modify my function to :

function SearchArray(NamaArray, SKey, SValue, ReturnKey){
    var index1 = -1;
    for (var i = 0; i < NamaArray.length; i++) {
        if (NamaArray[i].SKey == SValue){
            index1 = i
            i = NamaArray.length;
        } 
    }
    var ReturnValue;
    if (ReturnKey == 0){
        ReturnValue = index1
    }else{
        ReturnValue = NamaArray[index1].ReturnKey;
    }
    return ReturnValue
} 

It's error or no value return (index1 is -1) Please help me. I call this method like this

var a = SearchArrayBasedID(myarray, 100, 0)  --> return : 0
var b = SearchArray(myarray, "ID", 100, 0)   --> return : -1
Firdaus
  • 43
  • 6
  • 3
    The problem is your use of the variable SKey. `if (NamaArray[i][SKey] == SValue)` – James Nov 02 '15 at 16:51
  • because i want to use that function to search based on other parameter. not just "ID", like "nama" or "AData" property – Firdaus Nov 02 '15 at 16:53
  • 1
    @Firdaus: That's what you should explain in your question. Don't just say "but if I change it to this, it doesn't work" and leave it on us to figure out what changed (and why). – Felix Kling Nov 02 '15 at 16:54
  • You can use the variable, but it needs to be in brackets, otherwise the `if` is looking for a property called "SKey", instead of a property called (the value IN SKey). – James Nov 02 '15 at 16:56
  • @Felix Kling.. Ok my false... sory – Firdaus Nov 02 '15 at 17:04

1 Answers1

1
if (NamaArray[i].SKey == SValue){

should be

if (NamaArray[i][SKey] == SValue){

because the access of a variable as property requires brackets.

Nina Scholz
  • 376,160
  • 25
  • 347
  • 392