Jits Jits - 1 year ago 44
JSON Question

JSON response incorrectly matches partial key for color data

Below java script code matches to "COMPLETED" due to jsonData.search(key) !== -1 which is wrong because json response doesn't contain COMPLETED, it should show red color instead of green in the output.


Getting specific color for specific value using JSON data



Output: ["green", "red"]

Expected: ["red"]




const colorMap = {
COMPLETED: 'green',

Object.keys(colorMap).forEach((key, index) => {
if (jsonData.search(key) !== -1) {

Actual output:

Color key matches to "COMPLETED - green" first due to search(key).

Expected output:

Color key should match to "NOT_COMPLETED - red" first.

Can someone please help me to match with NOT_COMPLETED - read color instead of COMPLETED - green color? Thanks in advance!

Answer Source

This https://jsfiddle.net/xq7hLo6h/6/ fixes the issue by simply searching the JSON string for "KEY" (with quotes) instead of KEY:

if (jsonData.search("\"" + key + "\"") >= 0) { /* ... */ }

This way the problem with COMPLETED being found inside "NOT_COMPLETED" is circumvented.

However a more robust way would be to actually parse the JSON string in order to get the object and then check the actual property.