2016-11-15 85 views
0

在下面的陣列中,我有一個鍵/值對如何從具有鍵/值對對象的數組中獲取值?

var options = [{ 
    key: "select", 
    value: null 
}, { 
    key: "one", 
    value: "First Option" 
}, 
{ 
    key: "second", 
    value: "Second Option" 
}]; 

如何讓基於從選項數組鍵的值對象?

例如,如果密鑰是「select」,它應該返回null,如果密鑰是「one」,它應該返回「第一選項」爲 。

+0

@Jaromanda X感謝 – MemoryLeak

回答

2

ES6有陣列查找功能:

var val = options.find(function(o){ return o.key==="select" }).value; 

也許在你自己的函數把它包使其更具可重用性:

function findValue(arr, key){ 
    return arr.find(function(o){ return o.key===key }).value; 
} 

var val = findValue(options,"select"); 

我會認爲這是最沒有修改原始數組的最正確的答案,但您現在必須意識到有很多方法可以爲這隻貓蒙皮。 (我喜歡Zubiac Zubeda的回答,因爲它是一個簡單的for-loop如此快速和向後兼容,並且具有跳過不必要迭代的突破。)

1

你必須通過他蠻力它...

function findValueForOption(key) { 
    for (i = 0; i < options.length; i++) { 
     if (options[i].key === key) { 
      return options[i].value; 
     } 
    } 
    return null; // Or do whatever you feel is appropriate when an unspecified key is requested... 
} 
0

使用forEach循環JSON ..

有做這件事的多種方式。

這是方式

var options = [{ 
     key: "select", 
     value: null 
    }, { 
     key: "one", 
     value: "First Option" 
    }, 
    { 
     key: "second", 
     value: "Second Option" 
    }]; 
    options.forEach(function(item){ 
    console.log(item.value) 

    }) 

DEMO

2

你可以搜索你的陣列所需的對象之一,然後獲取該對象的值:

var value; 

// Loop through the options array 
for (var i = 0; i < options.length; i++) { 
    // If the key for this iteration's element is desired 
    if (options[i].key == "select") { 
     // Set the value to appropriately and exit the loop 
     value = options[i].value; 
     break; 
    } 
} 

這代碼根據您的密鑰使「值」等於您想要的值。如果要多次確定該值,可以將代碼包裝在函數中並返回值。您可能還想爲所需的密鑰添加參數,並用"options[i].key == <parameter name>"替換options[i].key == "select"

或者,你可以組織你的對象,像這樣:

var options = { 
    "select": null, 
    "one": "First Option", 
    "second": "Second Option" 
}; 

有了這個,你可以訪問所需的鍵的值,像這樣:

options[<desired key>] 

所以,options["select"]將返回null

+1

感謝您的回答和建議,在我的情況下,它是一個JSON數據 – MemoryLeak

+0

嗯,好,我很高興我能提供有用的信息。祝你的項目好運! –

0

您可能需要考慮重組您的數據。看來你拿了鑰匙,價值從字面上:

如果你組織你的數據是這樣的:

var options = [ 
    { 
    select: null 
    }, 
    { 
    one: 'first option' 
    } 
]; 

您只需調用options.select檢索值。

+2

這個JSON更具可讀性並且更易於遍歷,是的,但是也許他是從API(或其他他無法更改的)獲取它的。 –

2

使用Array.prototype.filter(現代瀏覽器和IE9 +):

options.filter(function(opt) { 
    return opt.key === 'one'; 
})[0].value; 

或者使用ES6箭頭符號一個班輪:

options.filter(opt => opt.key === 'one')[0].value; 

可重複使用的函數,返回null如果沒有找到匹配:

function findValueByKey(opts, key) { 
    var match = opts.filter(function(opt) { 
    return opt.key === key; 
    }); 
    return match[0] ? match[0].value : null; 
} 

JSFiddle:https://jsfiddle.net/02oawajt/3/

+0

如果找不到任何選項,則會引發錯誤 – SReject

+0

良好的調用,我更新了可重用函數。謝謝! – MusikAnimal

1

Arraymap使用發現keyvalue

var options = [{ 
 
    key: "select", 
 
    value: null 
 
}, { 
 
    key: "one", 
 
    value: "First Option" 
 
}, 
 
{ 
 
    key: "second", 
 
    value: "Second Option" 
 
}]; 
 

 

 

 
var run = options.map(function (item,index) { 
 
    var fullname = 'the key='+item.key+',and value='+item.value; 
 
    return fullname; 
 
}) 
 
console.log(run);

0

如果您不介意依賴關係,則可以將數組轉換爲適當的Object使用Lodash _.fromPairs

pairs = options.map(o => [o.key, o.value]) 
// [["select", null], ["one", "First"], ["two", "Second"]] 

_.fromPairs(pairs) 
// { select: null, one: "First", second: "Second" } 
0

我希望這會爲你工作

function getValue(keyName) { 

    if(!keyName) return '' 

    var value = _.find(options, function(obj){ 
     if(obj.key === keyName) { 
      return true 
     } 
    }) 

    if(value === undefined) return '' 

    return value.value 
} 

var a = getValue('one') 

檢查片段的工作示例。

$(function(){ 
 
    var options = [{ 
 
     key: "select", 
 
     value: null 
 
    }, { 
 
     key: "one", 
 
     value: "First Option" 
 
    }, 
 
    { 
 
     key: "second", 
 
     value: "Second Option" 
 
    }]; 
 
    
 
    function getValue(keyName) { 
 
    
 
     if(!keyName) return '' 
 

 
     var value = _.find(options, function(obj){ 
 
      if(obj.key === keyName) { 
 
       return true 
 
      } 
 
     }) 
 
    
 
     if(value === undefined) return '' 
 
    
 
     return value.value 
 
    } 
 
    
 
    var a = getValue('one') 
 
    console.log(a) 
 
    })
<script src="http://underscorejs.org/underscore.js"></script> 
 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

0

對於老/ ES3環境:

function find(arr, key) { 
    for (var i = 0; i < arr.length; i += 1) { 
     if (arr[i].key === key) { 
      return arr[i].value; 
     } 
    } 
} 

對於新/ ES5環境:

function find(arr, key) { 
    return (arr.filter(function(item) { return item.key === key})[0] || {}).value; 
} 
0

這是做它的一種方式。我已經通過程序改變了它的結構,然後訪問新的結構。

var options = [{ 
    key: "select", 
    value: null 
}, { 
    key: "one", 
    value: "First Option" 
}, 
{ 
    key: "second", 
    value: "Second Option" 
}]; 

function changeStructure(obj){ 
    var newObj = {}; 
    obj.forEach(function(val, index){ 
      newObj[val['key']] = val['value']; 
    }); 
    return newObj; 
} 

var newStructure = changeStructure(options); 

新格局:

{ 
     one : "First Option" 
     second:"Second Option" 
     select:null 
} 

現在,您可以使用鍵訪問它:

console.log(newStructure['select']); or console.log(newStructure.select) 

JS Fiddle

0

var options = [{ 
 
    key: "select", 
 
    value: null 
 
}, { 
 
    key: "one", 
 
    value: "First Option" 
 
}, { 
 
    key: "second", 
 
    value: "Second Option" 
 
}]; 
 

 
// output values of whatever you like 
 
checkValue("select"); 
 
console.log("------------------------------"); 
 
checkValue("one"); 
 
console.log("------------------------------"); 
 
checkValue("second"); 
 
console.log("------------------------------"); 
 

 
function checkValue(val) { 
 
    for (var i = 0; i < options.length; i++) { 
 
    
 
    if(options[i].key == val){ 
 
     console.log("VALUE IS: " + options[i].value); 
 
    } 
 
    
 
    } 
 

 
}

-1

您可以使用for..of循環。

var options = [{ 
 
    key: "select", 
 
    value: null 
 
}, { 
 
    key: "one", 
 
    value: "First Option" 
 
}, { 
 
    key: "second", 
 
    value: "Second Option" 
 
}]; 
 

 
let filter = (array, prop, res = void 0) => { 
 
    for (let {key, value} of array) prop === key && (res = value); return res 
 
} 
 

 
console.log(filter(options, "select")); 
 
console.log(filter(options, "one")); 
 
console.log(filter(options, "second"));