2017-02-03 76 views
1

所以,我從JSON中的REST API獲取這些數據。我將以此爲例。選擇陣列對象的道具

var JsonCategoriaHot = { 
    "products": [ 
     {"id": 8, 
     "id_manufacturer": "0", 
     "manufacturer_name": "Fashion Manufacturer", 
     "id_supplier": "0", 
     "id_category_default": "Isso terá de ser uma URL ou um nome", 
     "new": "null", 
     "images": "ur.presta.com", 
     "name": [{"id": "1", "value": "Printed Summer Dress"}, 
        {"id": "2", "value": "Vestido estampado de verão"}], 
     "description": [{"id":"1","value":"Ensaio do Muzenza"}],}, 
     {"id":1}, // just empty data to represent "something" 
     {"id":2}, 
     {"id":3}, 
     {"id":4}, 
     {"id":5}, 
     {"id":9, 
     "name": "Michel Conrado", 
     "images": "ur.presta.com/michelconrado", 
     "manufacturer_name": "Muzenza", 
     "category_default": "mudar de cat_default para url", 
     "description": "Essa é uma descrição" 
     }, 
     {"id":12, 
     "name": "12 Michel Conrado", 
     "images": "ur.presta.com/michelconrado", 
     "manufacturer_name": "Muzenza", 
     "category_default": "mudar de cat_default para url", 
     "description": "Essa é uma descrição" 
     } 
    ] 
}; 

因此,從這些數據我想映射一些對象。並更改一些字符串的名稱。有了下面這段代碼:

var idparaurl = JsonCategoriaHot.products.map(function(products,i) { 
    return { 
     index: i + 1, 
     name: products.name, 
     image: products.images, 
     fabricante: products.manufacturer_name, 
     catgdf: products.id_category_default, 
     desc: products.description, 
    }; 
}); 

現在我需要「選擇」屬性「名」選擇此情況下,默認的ID將是「產品」>「名稱」> ID> 2>值>字符串。

這就像一個「減少」,並從「名稱」數組中選擇一個值。

也許將來會有更多的語言支持。所以每個ID都表示來自我的CMS的每種對應語言的翻譯。

它應該返回(每個對象 - 所有映射的數據會是這樣):

[ 
    { 
     "catgdf": "Isso terá de ser uma URL ou um nome tidpo Muzenza", 
     "image": "ur.presta.com", 
     "index": 1, 
     "name": "Vestido estampado de verão", 
     "desc": [ 
      { 
       "id": "1", 
       "value": "Ensaio do Muzenza" 
      } 
     ], 
     "fabricante": "Fashion Manufacturer" 
    } 

    //... 
] 

「描述」陣列I將應用此溶液也所以我應該是這樣的物鏡內:

//... 
    "desc": "Ensaio do Muzenza" 
} 
+0

地圖是否迭代對象? –

+0

嗨!拉吉納撒尼剛剛解決了我的情況。謝謝! –

回答

1

我建議使用filter操作而不是使用reduce

這裏是一個會工作的函數:

function parseArrayKeyIndexValue(valArray, id) { 
    if (!(valArray instanceof Array)) { 
    return valArray; 
    } 
    return valArray.filter(function(valArrayItem){ 
    if (valArrayItem.id === id) { 
     return true; 
    } 
    })[0].value; 
} 

在您的示例中的地圖是這樣的:

var idparaurl = JsonCategoriaHot.products.map(function(products,i) { 
    return { 
     index: i + 1, 
     name: parseArrayKeyIndexValue(products.name, "2"), 
     image: products.images, 
     fabricante: products.manufacturer_name, 
     catgdf: products.id_category_default, 
     desc: parseArrayKeyIndexValue(products.description, "1"), 
    }; 
}); 

的代碼可以與你提供的「JsonCategoriaHot」示例數據在運行此jsbin:http://jsbin.com/zapimineje/edit?js,console,output

+0

哇!有用!!!非常感謝!對不起,如此新手,我認爲這不是一個複雜的問題。我正在努力學習4個月的Javascript。 你教這個我很多!非常感謝! –