我有一个数组,其中每个条目都是汽车名称,并且我有一个 json 对象/字符串,其中包含相同的汽车名称,后跟颜色属性。
如何检查数组中的每辆车是否包含在 JSON 字符串中并依次返回与其关联的颜色?非常感谢您的帮助!
我的代码是这样的:
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]);
}
}
}
我的 JSON 文档如下所示:
{
"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)"}
]
},