I have a array object I want to return and if it will find in this array otherwise it will return or I want to just return value not key.
Currently it returns an object and I need only a value.
const arrObj = [
{
"relation_type": "undefined"
},
{
"relation_type": "or"
},
{
"relation_type": "and"
},
{
"relation_type": "or"
},
{
"relation_type": "or"
}
]
let obj = arrObj.find((o) => {
if (o.relation_type === "and") {
return true;
}
});
console.log(obj);
halfer
20.2k20 gold badges111 silver badges208 bronze badges
asked Oct 4, 2022 at 15:14
Rohit Verma
3,7918 gold badges45 silver badges90 bronze badges
3 Answers 3
You could do something like that :
let obj = arrObj.find(o => o.relation_type === "and") ? "and" : "or"
Sign up to request clarification or add additional context in comments.
4 Comments
Felix Kling
"One way to achieve this would be to return o.relation_type instead of true inside your obj variable." I assume you are referring to the call to
.find but no, that's not how .find works. It doesn't return the value returned from the callback.Felix Kling
arrObj.find(o => o.relation_type === "and").relation_type would always return "and" or throw an error.Rohit Verma
@rmfy what about if there is "and" not available in array?
rmfy
@FelixKling you're right, updated my OP !
Maybe we can simply use destruction:
let {relation_type} = arrObj.find((o) => {
if (o.relation_type === "and") {
return true;
}})
Comments
You can use the .map method and loop over and access the relation type as a property here is a working example
const arrObj = [
{
"relationtype": "undefined"
},
{
"relationtype": "or"
},
{
"relationtype": "and"
},
{
"relationtype": "or"
},
{
"relationtype": "or"
}
]
{arrObj.map((object,index)=>
console.log(object.relationtype)
)}
Comments
lang-js
const result = arrObj.some(o => o.relation_type === 'and') ? 'and' : 'or'.