2016-07-15 80 views
1

我呼籲供應商的對象,其中的ID始終是唯一如下:如何從其中子對象的ID是已知的對象中檢索子對象

var suppliers = { 
    Supplier1: { 
     id: 1, 
     name: 'Supplier1', 
     SVGTemplate: 'svg-supplier1' 
    }, 
    Supplier2: { 
     id: 2, 
     name: 'Supplier2', 
     SVGTemplate: 'svg-supplier2' 
    }, 
    Supplier3: { 
     id: 3, 
     name: 'Supplier3', 
     SVGTemplate: 'svg-supplier3' 
    } 
} 

我怎樣才能返回子對象(例如返回供應商。供應商1)當我知道的只是子對象的ID?我試圖用.filter,但似乎只對數組工作:

function findById(source, id) { 
    return source.filter(function (obj) { 
     return +obj.id === +id; 
    })[0]; 
} 

var supplierarray = findById(suppliers, myKnownID); 
return supplierarray; 

回答

2

您使用for-in循環需要循環的object,您嘗試使用.filter這是數組。

所以你可以改變findById定義如下

var suppliers = { 
    Supplier1: { 
     id: 1, 
     name: 'Supplier1', 
     SVGTemplate: 'svg-supplier1' 
    }, 
    Supplier2: { 
     id: 2, 
     name: 'Supplier2', 
     SVGTemplate: 'svg-supplier2' 
    }, 
    Supplier3: { 
     id: 3, 
     name: 'Supplier3', 
     SVGTemplate: 'svg-supplier3' 
    } 
} 
// Should return single object not array, as id is unique as OP said 
function findById(source, id) { 
    for(var key in source){ 
    if(source[key].id === id){ 
     return source[key]; 
    } 
    } 
    return null; 
} 

findById(suppliers,3);// {id: 3, name: "Supplier3", SVGTemplate: "svg-supplier3"} 
+0

感謝JagsSparrow,它已經完全返回了對象,就好像我已經寫了返回供應商。供應商1的ID爲1,這意味着我不必爲每個供應商對switch語句進行硬編碼。乾杯。 – RussAwesome

0
Object.keys(suppliers).map(key => suppliers[key]).find(({id}) => id === someId); 
+0

雖然此代碼片段可能會解決問題,但[包括解釋](// meta.stackexchange.com/questions/114762/explaining-entirely-code-based-answers)確實有助於提高帖子的質量。請記住,您將來會爲讀者回答問題,而這些人可能不知道您的代碼建議的原因。也請儘量不要使用解釋性註釋來擠佔代碼,因爲這會降低代碼和解釋的可讀性! – FrankerZ

0

您可以搜索其子對象的任何鍵。

Object.prototype.findBy = function(propName, propVal){ 

    for(var i in this){ 

     if(this[i][ propName ] == propVal){ 
      return this[i]; 
     } 
    } 
    return undefined; 
}; 

var suppliers = { 
    Supplier1: { 
     id: 1, 
     name: 'Supplier1', 
     SVGTemplate: 'svg-supplier1' 
    }, 
    Supplier2: { 
     id: 2, 
     name: 'Supplier2', 
     SVGTemplate: 'svg-supplier2' 
    }, 
    Supplier3: { 
     id: 3, 
     name: 'Supplier3', 
     SVGTemplate: 'svg-supplier3' 
    } 
} 

console.log(suppliers.findBy("id",1)); 

這裏我已經在根對象的原型中添加了函數。