I have an array where every entry is a car name and I have a json object/string that contains those same car names followed by colour properties.
How can I check for each car in the array whether it is contained in the JSON string and return the colours associated with it one after another? Thanks very much for any help!
My code is like this:
var allCars;
var inputCount = 1;
$(document).ready(function() {
$.getJSON('cars.json', function(data) {
console.log (data);
allCars = data;
createInputField();
$('form').submit(function(){
getCarColours()
});
})
}
);
function createInputField()
{
$('.button').before('<select id="cars'+ inputCount +'" name="cars'+ inputCount +'" class="cars"></select> - <select id="percentage'+ inputCount +'" name="percentage'+ inputCount +'" class="percentage"></select><br />');
$('.cars').append('<option value="'+ 0 +'">Please select a country </option>');
for (var i = 0; i < allcars.cars.length; i++) {
$('.cars').append('<option value="'+ allcars.cars[i].name +'">'+ allcars.cars[i].name +'</option>');
}
inputCount += 1
}
function getCarColours(){
var carsSelected = [];
for( var y = 1; y < inputCount; y++){
carsSelected.push($('select[name="cars'+ y +'"]').val());
}
for (var i = 0; i < allcars.cars.length; i++) {
if allcars.cars.has(carsSelected[i]{
console.log(carsSelected[i]);
}
}
}
My JSON document looks like this:
{
"cars" :
[
{
"name": "Merc",
"colour" : [
{"name":"green", "percent":35, "rgb":"rgb(0,153,0)"},
{"name":"red", "percent":31, "rgb":"rgb(191,0,0)"},
{"name":"black", "percent":32, "rgb":"rgb(0,0,0)"},
{"name":"white", "percent":2, "rgb":"rgb(255,255,255)"}
]
},
{
"name": "BMW",
"colour" : [
{"name":"red", "percent":90, "rgb":"rgb(216,17,38)"},
{"name":"black", "percent":10, "rgb":"rgb(0,0,0)"}
]
},