1

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);

3
  • 1
    could you write what you expect exactlly? Commented Oct 4, 2022 at 15:15
  • 5
    If I understand that correctly you want something like const result = arrObj.some(o => o.relation_type === 'and') ? 'and' : 'or'. Commented Oct 4, 2022 at 15:17
  • Thanks you @Felix Kling it working fine as I want. Commented Oct 4, 2022 at 15:24

3 Answers 3

5

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

"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.
arrObj.find(o => o.relation_type === "and").relation_type would always return "and" or throw an error.
@rmfy what about if there is "and" not available in array?
@FelixKling you're right, updated my OP !
2

Maybe we can simply use destruction:

let {relation_type} = arrObj.find((o) => {
  if (o.relation_type === "and") {
    return true;
  }})

Comments

1

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)
    )}

.map() MDN Docs

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.