absynthe minded web smith absynthe minded web smith - 5 months ago 54
JSON Question

JavaScript/jQuery find JSON key/value with partial match of variable and return value

I have a list of models I want to search through and pull the url for the correct one. I won't always have the full key, and never the full value, but will always have at least a unique part of it.

Right now the code is just in test mode, with a set number that matches a key, print a success or failure.

The console keeps telling me that models[i].indexOf isn't a function. I know it's an object, but when I do a toString on it, I get "object Object". What am I not understanding?

I'm happy with a solution that is either vanilla JavaScript or uses jQuery.

The code:

if ($('.mobile_tutorial').length) {
var device = /*$device.model*/ "NTZEZ717VLU", model_code = device.substr(2).substr(0,device.length-3);
$.ajax({
url: "/scripts/phone_models.json",
type: 'get',
dataType: 'json',
success: function (data) {
var models = data.Manufacturer;
for (var i = models.length - 1; i >= 0; i--) {
if (models[i].indexOf(model_code) > -1) {
console.log(models[i])
} else {
console.log('no match')
}
}
}
});
}


The JSON (partial):

{
"Manufacturer": [{
"ZEZ955L": "http://x.com/mobile/home.seam?custId=ZEZ955L"
}, {
"ZEZ990G": "http://x.com/mobile/home.seam?custId=ZEZ990G"
}, {
"ZEZ828TL": "http://x.com/mobile/home.seam?custId=ZEZ828TL"
}, {
"ZEZ716BL": "http://x.com/mobile/home.seam?custId=ZEZ716BL"
}, {
"ZEZ717VL": "http://x.com/mobile/home.seam?custId=ZEZ717VL"
}, {
"ZEZ962BL": "http://x.com/mobile/home.seam?custId=ZEZ962BL"
}, {
"ZEZ963VL": "http://x.com/mobile/home.seam?custId=ZEZ963VL"
}]
}

Answer

You would need to grab the value of the key changing models[i].indexOf(model_code) to Object.keys(models[i])[0].indexOf(partial_model_code). Here's it in action:

var partial_model_code = '3VL'

function ajax(data) {
  var models = data.Manufacturer;
  for (var i = models.length - 1; i >= 0; i--) {
    
    // grab the keys in the object
    // since there will only be one object grab the first one
    // check if the key partially matches
    if (Object.keys(models[i])[0].indexOf(partial_model_code) > -1) {
      console.log(models[i])
    } else {
      console.log('no match')
    }
  }
}


var data = JSON.parse(`{
    "Manufacturer": [{
            "ZEZ955L": "http://x.com/mobile/home.seam?custId=ZEZ955L"
        }, {
            "ZEZ990G": "http://x.com/mobile/home.seam?custId=ZEZ990G"
        }, {
            "ZEZ828TL": "http://x.com/mobile/home.seam?custId=ZEZ828TL"
        }, {
            "ZEZ716BL": "http://x.com/mobile/home.seam?custId=ZEZ716BL"
        }, {
            "ZEZ717VL": "http://x.com/mobile/home.seam?custId=ZEZ717VL"
        }, {
            "ZEZ962BL": "http://x.com/mobile/home.seam?custId=ZEZ962BL"
        }, {
            "ZEZ963VL": "http://x.com/mobile/home.seam?custId=ZEZ963VL"
    }]
}`)

ajax(data)

I hope that helps!

Comments