![](/img/trans.png)
[英]Find the first unused property value in an array of javascript objects
[英]Find property value in array of objects (Javascript)
我有以下對象數組。 我想檢查objArray
存在什么 errorCode 值。
var objArr = [
{
"7364234": "hsjd",
"errorCode": "400"
},
{
"12345": "jd",
"errorCode": "500-001"
}
]
以下是查找關鍵errorCode
是否存在於對象數組中的解決方案。 如果我執行如下所示的 console.log,我會得到想要的結果。
const contains = (string) =>
objArr.findIndex(
// Is the string contained in the object keys?
obj => Object.keys(obj).includes(string)
) !== -1
console.log(contains('errorCode')) // returns true
console.log(contains('spaghetti')) // returns false
但我想知道objArray
存在 errorCode 的值。 例如,我想知道errorCode: "500-001"
是否存在於objArray
。 我怎樣才能得到這個結果? 有人可以建議嗎?
您可以使用Array.prototype.some
如下。
var objArr = [ { "7364234": "hsjd", "errorCode": "400" }, { "12345": "jd", "errorCode": "500-001" } ]; const contains = (keyVal) => objArr.some(({ errorCode }) => errorCode.includes(keyVal)); console.log(contains("500"));
循環遍歷每個元素並檢查它是否包含您要查找的代碼:
function hasErrorCode( errorCode ) {
var r = false; // assume
objArr.forEach( function( o ) {
if ( o.errorCode == errorCode ) {
r = true;
}
} );
return r;
}
console.log( hasErrorCode( '400' ) ); // true
console.log( hasErrorCode( 'asdfasdf' ) ); // false
這可以通過使用標准for
循環並在找到代碼時使用break
退出來提高效率。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.