简体   繁体   English

如何检查对象的值

[英]How to check an object for a value

Hey I created my first app in react native and i run into some trouble, i simple would like to know how i can check an object for an specific value from a local storage. 嘿,我在react native中创建了我的第一个应用程序,遇到了一些麻烦,我很想知道如何从本地存储中检查对象的特定值。 This is what i have so far, i know its not that much. 这是我到目前为止所拥有的,我知道的还不多。

handleClick = (item)=>{
store.get('myobject').then((res) =>
console.log(res)
)

this is my res object: 这是我的res对象:

[
{ id: '456', p: 'hey' },
{ id: '464', p: 'ho' },
{ id: '467', p: 'lets' },
{ id: '263', p: 'go' }
]

and as example i would like to know, if id 467 is in the object. 作为示例,我想知道ID 467是否在对象中。

You could make use of the some method of Array: 您可以使用Array的some方法:

 var res = [ { id: '456', p: 'hey' }, { id: '464', p: 'ho' }, { id: '467', p: 'lets' }, { id: '263', p: 'go' } ]; var found = res.some(item => item.id === '467'); console.log(found); 

Essentially, as it is stated here 从本质上讲,因为它是说这里

The some() method tests whether at-least one element in the array passes the test implemented by the provided function. some()方法测试数组中至少一个元素是否通过了由提供的函数实现的测试。

You could do a forEach loop and check for your desired value: 您可以执行forEach循环并检查所需的值:

 var res = [ { id: '456', p: 'hey' }, { id: '464', p: 'ho' }, { id: '467', p: 'lets' }, { id: '263', p: 'go' } ] function containsCheck(array) { var found = false; array.forEach(function(element) { if (element.id === '467') { found = true; } }); return found; }; console.log(containsCheck(res)); 

作为替代方案,您可以检查Lodash 。使用集合或对象时,此lib是项目中不错的东西。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM