从JavaScript中获取数组/对象的信息

时间:2015-04-13 16:06:57

标签: javascript

{
  brandBrandId: {
    brandId: 2,
    brandName: "Hikka",
    isGun: true
  },
  modelId: "1",
  modelName: "Hikka model"
}, {
  brandBrandId: {
    brandId: 3,
    brandName: "Bebrand",
    isGun: true
  },
  modelId: "2",
  modelName: "Bebrand model 1"
}, {
  brandBrandId: {
    brandId: 2,
    brandName: "Hikka",
    isGun: true
  },
  modelId: "3",
  modelName: "Hikka model2"
}

的javascript

var models = $scope.models;
console.log("selectedBrand---->" + selectedBrand);
    for (var i = 0; i < models.length; i++) {
    console.log(i+" : " +[i].brandBrandId.brandId)//ERROR HERE!

错误 TypeError:无法读取属性&#39; brandId&#39;未定义的

问题

如何使用JavaScript搜索品牌2下的模型?就像给我每个有brandId=2的模型一样。我试图循环它,但我真的不能这样做,我希望有一些更好,更明智的方法来做到这一点。我需要特定品牌下的每个modelIdmodelName。谢谢!

解决方案

function getModels() {
                    var brandsmodels=new Array();
                     for (var i = 0; i < models.length; i++) {

                        if (models[i].brandBrandId.brandId === selectedBrand) {
                            brandsmodels.push({
                                "modelId": ""+models[i].modelId,
                                "modelName": ""+models[i].modelName,
                                "brandId": ""+selectedBrand
                            });

                        }
                    }
                    $scope.brandsmodels=brandsmodels;

                }

1 个答案:

答案 0 :(得分:0)

您可以使用过滤器数组方法:

input.filter(function(model) {
   return model.brandBrandId.brandId == 2;
});