admin管理员组

文章数量:1406444

I am using the ._get lib to check for two values in an object and then return the default one based ONLY IF BOTH those 2 are empty.

For example, I have an object;

const obj = { person: { firsName: 'John', lastName: '' }

_get(obj, 'person.firsName', 'noname')} ${_get(state, 
'person.lastName', 'noname')}

The problem here is that I will only get "noname noname" even if the person has ATLEAST one name empty.

How can i do something like this, especially consider that I am using it inside string literal:

`${_get(obj, '!person.firsName && !person.lasName', 'noname')} } `// pseudo

thanks

I am using the ._get lib to check for two values in an object and then return the default one based ONLY IF BOTH those 2 are empty.

For example, I have an object;

const obj = { person: { firsName: 'John', lastName: '' }

_get(obj, 'person.firsName', 'noname')} ${_get(state, 
'person.lastName', 'noname')}

The problem here is that I will only get "noname noname" even if the person has ATLEAST one name empty.

How can i do something like this, especially consider that I am using it inside string literal:

`${_get(obj, '!person.firsName && !person.lasName', 'noname')} } `// pseudo

thanks

Share asked May 8, 2018 at 9:47 FatahFatah 2,2864 gold badges21 silver badges40 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 3

Use _.get() without defaultValue to get both names, and then check if any of them exists before returning `noname':

const getName = (obj) => {
  const firstName = _.get(obj, 'person.firsName', '')
  const lastName = _.get(obj, 'person.lastName', '')

  return firstName || lastName ? `${firstName} ${lastName}`.trim() : 'noName';
}

const obj = { person: { firsName: 'John' } }
console.log(getName(obj)) // John
console.log(getName({})) // noname
<script src="https://cdnjs.cloudflare./ajax/libs/lodash.js/4.17.10/lodash.min.js"></script>

This is a generic method that gets multiple paths, filters the undefined values, and if the resulting array is empty, returns a defaultValue array:

const getMultiple = (obj, paths, defaultValue) => {
  const values = paths
    .map((path) => _.get(obj, path))
    .filter((v) => !_.isUndefined(v));

  return values.length ? values : [defaultValue];
}

console.log(
  getMultiple({ person: { firsName: 'John', lastName: 'Smith' }}, ['person.firsName', 'person.lastName'], 'noname').join(' ')
) // John Smith
console.log(
  getMultiple({ person: { firsName: 'John' }}, ['person.firsName', 'person.lastName'], 'noname').join(' ')
) // John
console.log(
  getMultiple({}, ['person.firsName', 'person.lastName'], 'noname').join(' ')
) // noname
<script src="https://cdnjs.cloudflare./ajax/libs/lodash.js/4.17.10/lodash.min.js"></script>

本文标签: javascriptHow to use lodash39s get method to check for 2 values of pathStack Overflow