Rohit Verma
Rohit Verma

Reputation: 3783

How to find a value from array object in JavaScript?

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

Upvotes: 1

Views: 115

Answers (3)

AndGoEdu
AndGoEdu

Reputation: 175

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

Upvotes: 1

rmfy
rmfy

Reputation: 173

You could do something like that :

let obj = arrObj.find(o => o.relation_type === "and") ? "and" : "or"

Upvotes: 5

Neighbor
Neighbor

Reputation: 65

Maybe we can simply use destruction:

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

Upvotes: 2

Related Questions