我在尝试将从查询字符串中获取的数组值与对象属性进行匹配时遇到问题,并在匹配时返回子对象。
我的阵列:
["model1-all", "model2-all", "model3-all"]
数组可以为空或返回一个,两个或所有值。
我的对象:
[
{
"model1-all": [
{
"text": "Model1",
"id": "model1-all",
"image": "http://example.com/images/model1/front.png",
"models": [
{
"id": "model1-all",
"text": "All",
"positiveFeatureCopy": null,
"negativeFeatureCopy": null,
"weight": 1000
},
{
"id": "model1-coupe",
"text": "Coupe",
"positiveFeatureCopy": null,
"negativeFeatureCopy": null,
"weight": 1000
},
{
"id": "model1-convertible",
"text": "Convertible",
"positiveFeatureCopy": null,
"negativeFeatureCopy": null,
"weight": 1000
}
]
}
],
"model2-all": [
{
"text": "Model2",
"id": "model2-all",
"image": "http://example.com/images/model2/front.png",
"models": [
{
"id": "model2-all",
"text": "All",
"positiveFeatureCopy": null,
"negativeFeatureCopy": null,
"weight": 1000
},
{
"id": "model2-hatchback",
"text": "Hatchback",
"positiveFeatureCopy": null,
"negativeFeatureCopy": null,
"weight": 1000
},
{
"id": "model2-convertible",
"text": "Convertible",
"positiveFeatureCopy": null,
"negativeFeatureCopy": null,
"weight": 1000
},
{
"id": "model2-estate",
"text": "Estate",
"positiveFeatureCopy": null,
"negativeFeatureCopy": null,
"weight": 1000
}
]
}
],
"model3-all": [
{
"text": "Model3",
"id": "model3-all",
"image": "http://example.com/images/model3/front.png",
"models": [
{
"id": "model3-all",
"text": "All",
"positiveFeatureCopy": null,
"negativeFeatureCopy": null,
"weight": 1000
},
{
"id": "model3-saloon",
"text": "Saloon",
"positiveFeatureCopy": null,
"negativeFeatureCopy": null,
"weight": 1000
},
{
"id": "model3-estate",
"text": "Estate",
"positiveFeatureCopy": null,
"negativeFeatureCopy": null,
"weight": 1000
}
]
}
]
}
]
我需要实现的是,当数组中的某个值与其中一个对象匹配时,例如, [{"model1-all" : [...
,我想返回它的子对象:
"models": [
{"id":"model1-all", "...":"....", "...", "...":"..."},
{"id":"model1-coupe", "...":"....", "...", "...":"..."},
{"id":"model1-convertible", "...":"....", "...", "...":"..."}
]
我可以使用jQuery或Underscore。
提前致谢
答案 0 :(得分:0)
不需要jQuery
var models = [];
var matches = ["model1-all", "model2-all", "model3-all"];
for (var key in data[0]) {
//No indexOf for IE8 compatibility
if (matches.indexOf(key) > -1) {
models.push({
id: key,
child: data[0][key]
});
}
//Not using indexOf
for (var i = 0; i < matches.length; i++) {
if (matches[i] == key) {
models.push({
id: key,
child: data[0][key]
});
break;
}
}
}
结果
models = [
{
id: "model1-all",
child: <object from model1-all>
},
..
]