2017-09-14 53 views
1

我想找到包含多個對象的數組中的對象的索引。我一直在努力爭取了一段時間,並將它簡化爲你所看到的並且仍然無法獲得的東西。請讓我知道什麼工作,這樣我可以從matchBetween("string1");findIndex javascript問題

matchBetween("string1"); 
matchBetween = function (result) { 
     let params = [ 
      { param: "string1", input: "inputstring1"}, 
      { param: "string2", input: "inputstring2"} 
      ]; 
     console.log(result, params, params.param); //Output: "string1", (2)[{...}, {... 
     let location = params.findIndex (x => Object.is(result, x)); 
     console.log(location); //outputs -1 
     return params[location].input // 'Cannot read property 'input' of undefined' 
    }; 

我已經嘗試多種事態「輸入」對象的字符串,但我覺得這是一個簡單的辦法,我只是缺少它。先謝謝你!

+1

你是Object.is將每個{param,input}對象與一個字符串進行比較...因此,顯然沒有匹配...'x => x.param == result'而不是 –

+1

note:'params .param'將始終未定義,因爲這不是對象數組的作用方式 –

回答

2

Object.is(result, x)是錯誤的。

運行params.findIndex (x => {console.log(x); return false;});,看看每個x看起來像

{param: "string1", input: "inputstring1"} 
{param: "string2", input: "inputstring2"} 

所以,你可以使用Object.is(result, x.param)吉恩提到的,或result === x.param,或者乾脆

params.find(x => x.param === result).input 

注意,你需要處理時,結果是未找到。

1

試試這個示例:

matchBetween = function (result) { 
 
    let params = [ 
 
     { param: "string1", input: "inputstring1"}, 
 
     { param: "string2", input: "inputstring2"} 
 
     ]; 
 
    console.log(result, params, params[0].param); //Output: "string1", (2)[{...}, {...x=>x.param == result 
 
    let location = params.findIndex (function(x) { return Object.is(result, x.param); }); 
 
    console.log(location); //outputs -1 
 
    return params[location].input // 'Cannot read property 'input' of undefined' 
 
}; 
 
console.log(matchBetween("string2"));