Leonel Matias Domingos
Leonel Matias Domingos

Reputation: 2070

Check if properties have value using lodash

How can I check if any value property has value?

[
  {
    "name": "DESIGEMPRESA",
    "value": ""
  },
  {
    "name": "DSP_DIRECAO",
    "value": ""
  },
  {
    "name": "MES",
    "value": ""
  }
]

Upvotes: 3

Views: 5146

Answers (5)

Chris Sprance
Chris Sprance

Reputation: 302

You can use _.find(collection, [predicate=_.identity], [fromIndex=0]) https://lodash.com/docs/4.17.4#find

  let x = [
    {
      "name": "DESIGEMPRESA",
      "value": "tr"
    },
    {
      "name": "DSP_DIRECAO",
      "value": ""
    },
    {
      "name": "MES",
      "value": ""
    }
  ]

  _.find(x, (o) => o.value.length > 0);

returns {name: "DESIGEMPRESA" , value: "tr"}

https://runkit.com/csprance/5904f9fcad0c6400123abaa2

Upvotes: 1

kind user
kind user

Reputation: 41913

You could use Array#some to check if at least one element hasn't empty value value.

var arr = [
  {
    "name": "DESIGEMPRESA",
    "value": ""
  },
  {
    "name": "DSP_DIRECAO",
    "value": ""
  },
  {
    "name": "MES",
    "value": ""
  }
],
res = arr.some(v => v.value != ''); //no object with not empty value

console.log(res);

Upvotes: 4

Adam Shone
Adam Shone

Reputation: 393

You don't need lodash:

arr.some(obj => Boolean(obj.value))

Upvotes: 3

Egor Stambakio
Egor Stambakio

Reputation: 18156

There is _.isEmpty() in lodash

    const a = [
      {
        "name": "DESIGEMPRESA",
        "value": ""
      },
      {
        "name": "DSP_DIRECAO",
        "value": ""
      },
      {
        "name": "MES",
        "value": ""
      }
    ]
    
    const r = a.map(x => _.isEmpty(x.value))
    
    console.log(r)
<script src="https://cdn.jsdelivr.net/lodash/4.17.4/lodash.min.js"></script>

Upvotes: 3

Rohith K P
Rohith K P

Reputation: 3561

var arr = [
  {
    "name": "DESIGEMPRESA",
    "value": ""
  },
  {
    "name": "DSP_DIRECAO",
    "value": ""
  },
  {
    "name": "MES",
    "value": "d"
  }
]

var out = arr.filter(function(obj){
  return obj.value
})

console.log(out)

Upvotes: 2

Related Questions