如何使用id / name从json商店中查找特定条目

时间:2017-12-05 18:45:02

标签: javascript json

如何使用id / name从json商店中查找特定条目?使用javascript函数

例如:

var products=[{
    "productId": 101,
    "productName": "Nilkamal Shoe Rack",
    "productPrice": 2223,
    "productOriginalPrice": 2470,
    "productDiscount": "20 %",
    "productColor": "Sandy Brown",
    "productSpecifications": [{
        "Brand": "Nilakamal",
        "Type": "Shoe Rack",
        "Material": "Polypropylene"
    }],
    "productServices": ["Installation and Demo not Required", "10 Days Replacement"]
},

{
    "productId": 102,
    "productName": "Seagate Backup Plus Slim 1TB wired external hard disk",
    "productPrice": 3899,
    "productOriginalPrice": 7450,
    "productDiscount": "47 %",
    "productColor": "White",
    "productSpecifications": [{
        "Brand": "Seagate",
        "Type": "External Hard Disk",
        "Capacity": "1 TB",
        "Connectivity": "USB 3.0",
        "Ports": "1 Port"
    }],
    "productServices": ["3 years warranty", "10 Days Replacement"]
}]

如何使用ID / name找到以下产品之一的所有详细信息?

1 个答案:

答案 0 :(得分:1)

你可以像这样使用array.find

 var myObj = products.find(obj => obj.productId == 102);
 console.log(myObj);

如果你想要功能那么

function getObjbyId(id){
     var myObj = products.find(obj => obj.productId == id);
     return myObj;
}