Reputation: 453
I have a function as below which traverse through a large chunk of json data.
const findMakeAndModel = (make, model) => {
let foundMakeModel = false;
makeModel.map(value => {
if (value.makeCode === make.toUpperCase()) {
value.model.map(makeModel => {
if (makeModel.modelValue === `${make} - ${model}`) {
foundMakeModel = true;
}
})
}
});
return foundMakeModel
}
Though it works, I would like to have the time cut down the time it takes. I tried to return inside the if (makeModel.modelValue === ${make} - ${model})
condition but somehow it doesn't work. Any help is appreciated.
Above json is what I'm using but actual one is much much more larger. That's why traversing through takes time.
Upvotes: 0
Views: 39
Reputation: 782099
There's no way to stop a map
or forEach
loop in the middle. If you want to stop the loop once you've found an element that meets a condition, you need to use a for
loop.
Or you can use the find
method. This returns the first element that meets a condition, so it will stop searching once that's found. You can then just check whether this is not null and return that.
Also, your variable is not an array, it's an object. You need to use data.makeModel
to get to the property with the array.
const findMakeAndModel = (make, model) => {
let makeUpper = make.toUpperCase(); // don't repeat this every time
let makeModelCombined = `${make} - ${model}`; // or this
let foundMakeModel =
data.makeModel.find(value => value.makeCode === makeUpper &&
value.model.find(makeModel => makeModel.modelValue === makeModelCombined))
return foundMakeModel !== null;
}
let data = {
"makeModel": [{
"makeId": 1,
"makeCode": "NISSAN",
"makeValue": "Nissan",
"model": [{
"modelCode": "NIS032",
"modelValue": "Nissan - Cube"
},
{
"modelCode": "NIS012",
"modelValue": "Nissan - March"
},
{
"modelCode": "NIS033",
"modelValue": "Nissan - Note CVT"
}
]
},
{
"makeId": 2,
"makeCode": "OPEL",
"makeValue": "Opel",
"model": [{
"modelCode": "OPE005",
"modelValue": "Opel - Zafira"
},
{
"modelCode": "OPE009",
"modelValue": "Opel - Astra"
}
]
},
{
"makeId": 21,
"makeCode": "DAIHATSU",
"makeValue": "Daihatsu",
"model": [{
"modelCode": "DAI006",
"modelValue": "Daihatsu - Terios 7"
},
{
"modelCode": "DAI015",
"modelValue": "Daihatsu - Extol"
},
{
"modelCode": "DAI007",
"modelValue": "Daihatsu - YRV Turbo"
},
{
"modelCode": "DAI010",
"modelValue": "Daihatsu - M303RS"
}
]
},
{
"makeId": 31,
"makeCode": "MITSUBISHI",
"makeValue": "Mitsubishi",
"model": [
{
"modelCode": "MIT042",
"modelValue": "Mitsubishi - Lancer Evo VIII"
},
{
"modelCode": "MIT009",
"modelValue": "Mitsubishi - i"
}
]
},
]
};
console.log(findMakeAndModel('Nissan', 'March'));
Upvotes: 3