Home > Enterprise >  How to find a value from array object in JavaScript?
How to find a value from array object in JavaScript?

Time:10-05

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 return Object & I need only 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);

Thanks for your support!

CodePudding user response:

You could do something like that :

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

CodePudding user response:

Maybe we can simply use destruction:

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

CodePudding user response:

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

  • Related