I have an object with duplicate key value pairs. I need to traverse it & evaluate index [0] only against a condition:

var cells = {"cells": [{"key": "-18", "key1": "-9", "key2": "-51", "key3": "23"}, {"key": 
"-18", "key1": "-9", "key2": "-51", "key3": "23"}, {"key": "-18", "key1": "-9", "key2": "-51", 
"key3": "23"}]};

My code so far:

var result = true;

if (cells instanceof java.util.List && !cells.isEmpty()) {
 for (var i = 0; i < cells.size(); i++) {
    var cell = cells.get(i);

    var key = cell.get("key");
    var primeKey = key.get[0];
    if (primeKey) {
        if (parseInt(primeKey) < 5) {
            result = false;
            break;
        }
    } else {
        result = false;
        break;
    }
}
} else {
result = false;
}

return result;

The error that I get is: Error encountered during evaluation: TypeError: Cannot read property "0.0" from undefined (#12)

1

There are 1 best solutions below

0
On BEST ANSWER

var primeKey = key.get[0]; is nonsensical as the "key" value pair is not an array to be iterated. However, if we simply change the i iterator to index 0 like so var cell = cells.get(0); we can evaluate the condition against index 0 only. No need to traverse the entire nested loop as we are only comparing against index 0. See below for details:

var cells = {"cells": [{"key": "-18", "key1": "-9", "key2": "-51", "key3": "23"}, {"key": 
"-18", "key1": "-9", "key2": "-51", "key3": "23"}, {"key": "-18", "key1": "-9", "key2": "-51", 
"key3": "23"}]};

var result = true;

if (cells instanceof java.util.List && !cells.isEmpty()) {
 for (var i = 0; i < cells.size(); i++) {
    var cell = cells.get(0);

    var key = cell.get("key");
    if (primeKey) {
        if (parseInt(primeKey) < 5) {
            result = false;
            break;
        }
    } else {
        result = false;
        break;
    }
}
} else {
result = false;
}

return result;