Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

sirbobz's avatar

Linking a JSON object to JavaScript Comparison and Logical Operators

I have a JSON Object {9: "1", 2: "4", 6: "5", 7: "3", undefined: ""} (question_id : question_answer) and Comparison and Logical Operator 9 < 2 || 7 < 3 && 6 == 4 (question_id, Comparison Operators, question_answer, Logical Operators) to test for true or false.

This is how it should work, get the question_id from the Comparison operator e.g (9 < 2) 9, check the value of the 9 from the JSON object e.g. (9: "1") 1. Replace the 9 with 1. Then the new comparison becomes 1 < 2;

Do for all the rest in the Comparison and Logical Operator.

Then finally check eval of the logic.

The JSON object is the users data and the Comparison and Logical Operator is the data to compare with.

Help, anyone? I am struggling to come up with this logic in Javascript.

0 likes
5 replies
bobbybouwmann's avatar

Wait... What are you trying to achieve here?

I think you're after something like this?

var json = {9: "1", 2: "4", 6: "5", 7: "3", undefined: ""};
var questionId = 9;
var answer = 2;
var comparison = '<';
var result = null;

if (json.hasOwnProperty(questionId)) {
    if (comparison === '<') {
        result = json[questionId] < answer;
    }
  
    if (comparison === '>') {
        result = json[questionId] > answer;
    }
  
    if (comparison === '=') {
        result = json[questionId] == answer;
    }
}

console.log(result);
sirbobz's avatar

Hello, I have this and such keys 9 < 2 || 7 < 3 && 6 == 4 or 10 < 5 || 7 < 4 && 1 == 4 could be any logic here. This is the logic to use to compare the users data in form of a JSON object.

The object is the form of {10: "1", 2: "4", 6: "5", 7: "3", undefined: ""}

So using the logic above, e.g. 10 < 5 || 7 < 4 && 1 == 4, get the value 10 and check it's corresponding value in the the object key/value which gives 1. Hence the new comparison becomes 1< 5 || 7 < 4 && 1 == 4

Do the same for the next comparison 7 < 4. Which should become 3 < 4 where 3 is the value to the key 7 on the object.

When all is done on the logic and comparison operations, now eval().

Thanks

bobbybouwmann's avatar

I honestly have no clue what your question is right now...

What have you tried so far yourself?

nolros's avatar

Sounds like a cut and paste from a homework assignment

Please or to participate in this conversation.