Check if properties matter with lodash

How to check if a value

property has a value

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

      

+3


source to share


5 answers




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)
      

Run codeHide result


+2


source


You don't need lodash:



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

      

+2


source


You can use Array#some

to check if at least one element has a null character 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);
      

Run codeHide result


+2


source


In lodash

there is _.isEmpty ()

    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>
      

Run codeHide result


+1


source


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

+1


source







All Articles