Home > Software design >  Lodash, method to return value from json array
Lodash, method to return value from json array

Time:02-11

I have to find inside a json array some value of a given key, and return the value of another key of the found object.

I have made this function:

const findValueByKey = ({
  jsonArray,
  keyToSearch,
  valueToSearch,
  keyOfTheValueToReturn,
  defaultMessage
}) => {
  const foundObject = jsonArray.find((obj) => obj[keyToSearch] === valueToSearch);
  if (foundObject) return foundObject[keyOfTheValueToReturn];
  return defaultMessage || 'not found';
};

But my question is if there's something similar with Lodash, I don't want to reinventing the wheel.

I know that I can find an object given some criteria, like:

_.find(jsonArray, (object) => object[keyToSearch] === valueToSearch);

But then I should extract the key that I need, etc.

CodePudding user response:

You can get the desired result using _.find along with _.get. _.find() will accept an object like { key: value } as the search criterion. Then we can use _.get() to return the desired property. If the key does not exist or the object cannot be found, we'll return defaultMessage.

The sample data comes from jsonplaceholder/users

let data = [ { "id": 1, "name": "Leanne Graham", "username": "Bret", "email": "[email protected]", "phone": "1-770-736-8031 x56442", "website": "hildegard.org", }, { "id": 2, "name": "Ervin Howell", "username": "Antonette", "email": "[email protected]", "phone": "010-692-6593 x09125", "website": "anastasia.net", }, { "id": 3, "name": "Clementine Bauch", "username": "Samantha", "email": "[email protected]", "phone": "1-463-123-4447", "website": "ramiro.info", }, { "id": 4, "name": "Patricia Lebsack", "username": "Karianne", "email": "[email protected]", "phone": "493-170-9623 x156", "website": "kale.biz", }, { "id": 5, "name": "Chelsey Dietrich", "username": "Kamren", "email": "[email protected]", "phone": "(254)954-1289", "website": "demarco.info", }, { "id": 6, "name": "Mrs. Dennis Schulist", "username": "Leopoldo_Corkery", "email": "[email protected]", "phone": "1-477-935-8478 x6430", "website": "ola.org", }, { "id": 7, "name": "Kurtis Weissnat", "username": "Elwyn.Skiles", "email": "[email protected]", "phone": "210.067.6132", "website": "elvis.io", }, { "id": 8, "name": "Nicholas Runolfsdottir V", "username": "Maxime_Nienow", "email": "[email protected]", "phone": "586.493.6943 x140", "website": "jacynthe.com", }, { "id": 9, "name": "Glenna Reichert", "username": "Delphine", "email": "[email protected]", "phone": "(775)976-6794 x41206", "website": "conrad.com", }, { "id": 10, "name": "Clementina DuBuque", "username": "Moriah.Stanton", "email": "[email protected]", "phone": "024-648-3804", "website": "ambrose.net", } ];

function findValueByKey (arr, keyToSearch, valueToSearch, keyOfTheValueToReturn, defaultMessage) { 
    const obj = _.find(arr, { [keyToSearch]: valueToSearch });
    return _.get(obj, keyOfTheValueToReturn, defaultMessage); 
}

console.log('Search by username:', findValueByKey(data, 'username', 'Samantha', 'name', 'Not found'))
console.log('Search by website:', findValueByKey(data, 'website', 'hildegard.org', 'name', 'Not found'))

console.log('Default result:', findValueByKey(data, 'keydoesntexist', 'valuedoesntexist', 'name', 'Not found'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.min.js" integrity="sha512-WFN04846sdKMIP5LKNphMaWzU7YpMyCU245etK3g/2ARYbPK9Ub18eG ljU96qKRCWh quCY7yefSmlkQw1ANQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>

And just for completeness, a vanilla JavaScript solution, using Array.find() along with the in operator

let data = [ { "id": 1, "name": "Leanne Graham", "username": "Bret", "email": "[email protected]", "phone": "1-770-736-8031 x56442", "website": "hildegard.org", }, { "id": 2, "name": "Ervin Howell", "username": "Antonette", "email": "[email protected]", "phone": "010-692-6593 x09125", "website": "anastasia.net", }, { "id": 3, "name": "Clementine Bauch", "username": "Samantha", "email": "[email protected]", "phone": "1-463-123-4447", "website": "ramiro.info", }, { "id": 4, "name": "Patricia Lebsack", "username": "Karianne", "email": "[email protected]", "phone": "493-170-9623 x156", "website": "kale.biz", }, { "id": 5, "name": "Chelsey Dietrich", "username": "Kamren", "email": "[email protected]", "phone": "(254)954-1289", "website": "demarco.info", }, { "id": 6, "name": "Mrs. Dennis Schulist", "username": "Leopoldo_Corkery", "email": "[email protected]", "phone": "1-477-935-8478 x6430", "website": "ola.org", }, { "id": 7, "name": "Kurtis Weissnat", "username": "Elwyn.Skiles", "email": "[email protected]", "phone": "210.067.6132", "website": "elvis.io", }, { "id": 8, "name": "Nicholas Runolfsdottir V", "username": "Maxime_Nienow", "email": "[email protected]", "phone": "586.493.6943 x140", "website": "jacynthe.com", }, { "id": 9, "name": "Glenna Reichert", "username": "Delphine", "email": "[email protected]", "phone": "(775)976-6794 x41206", "website": "conrad.com", }, { "id": 10, "name": "Clementina DuBuque", "username": "Moriah.Stanton", "email": "[email protected]", "phone": "024-648-3804", "website": "ambrose.net", } ];

function findValueByKey(arr, keyToSearch, valueToSearch, keyOfTheValueToReturn, defaultMessage) { 
    const obj = arr.find(el => (el || {}) [keyToSearch] === valueToSearch);
    return (keyOfTheValueToReturn in (obj || {})) ? obj[keyOfTheValueToReturn] : defaultMessage; 
}

console.log('Search by website:', findValueByKey(data, 'website', 'hildegard.org', 'name', 'Not found'))

  • Related