I'm trying to compare two JSON objects inside js. I've already manage to retrieve the info I desire into an array, since the two JSON objects are complex and not all the data has to be compared. However, in the for loop I'm trying to make for the goal, I don't know where to add the second loop for the second object, since including it inside the first object loop forces the objects to have the same length, and that's not true. Here's what I have so far:
var modelsJSON =
{
"modelsARRAY":
[
{
"modelData": {
"manufacture": "Renault",
"name": "Clio",
"year": 2018
},
"modelSpecs": {
"manualGear": true,
"turbo": false,
"diesel": false,
"gasoline": true
}
},
{
"modelData": {
"manufacture": "Renault",
"name": "Megane",
"year": 2019
},
"modelSpecs": {
"manualGear": true,
"turbo": true,
"diesel": false,
"gasoline": true
}
},
{
"modelData": {
"manufacture": "Renault",
"name": "Laguna",
"year": 2019
},
"modelSpecs": {
"manualGear": true,
"turbo": true,
"diesel": true,
"gasoline": false
}
}
]
};
var clientsJSON =
{
"clientsARRAY":
[
{
"clientData": {
"name": "Peter",
"lastName": "McKay",
},
"modelSpecs": {
"manualGear": true,
"turbo": true,
"diesel": true,
"gasoline": true
}
},
{
"clientData": {
"name": "John",
"lastName": "Lucas",
},
"modelSpecs": {
"manualGear": false,
"turbo": true,
"diesel": true,
"gasoline": false
}
}
]
};
var modelName = "";
var clientName = "";
var pdata = [];
var matches = 0;
for (var i in modelsJSON.modelsARRAY)
{
modelName += modelsJSON.modelsARRAY[i].modelData.name + " ";
for (var j in modelsJSON.modelsARRAY[i].modelSpecs)
{
pdata.push(modelsJSON.modelsARRAY[i].modelSpecs[j]);
}
}
console.log(modelName, pdata);
I'm trying to achieve a log like
"Client Peter has (3)matches with Clio car, (4)matches with Megane car and (x)matches with x car. \n Client John has (4)matches with Clio car, (2)matches with Megane car, and (y)matches with y car".
So I can format a new JSON with the result.
.forEach()is a basic for loop..map()is a for-loop that returns something for each element in the array..reduce()is a loop that turns an array into anything else, like a different array or an object..filter()turns an array into a different array with less elements. Et cetera.clients.forEach( client => client.specs.map( spec => models.find( models.specs.some( spec ))));basically meaning: for each client, find all the models that have at least one spec that the client wants. You can obviously do the same with for loops, but the code will be way longer and in my opinion less readable, since you'll have to create alot of temporary variables to store everything as you search through all the models.