How to use the pathOr function from ramda

Find comprehensive JavaScript ramda.pathOr code examples handpicked from public code repositorys.

The ramda.pathOr function returns the value at the specified path of an object, or a default value if the path is not found or the value is undefined.

61
62
63
64
65
66
67
68
69
  return
}

const comments = [`# ${pathOr(key, [...path, "title"], schema)} ##`, ""]

const description = pathOr("", [...path, "description"], schema)
if (description) {
  comments.push(" " + description.split("\n").join("\n "), "")
}
fork icon286
star icon104
watch icon0

+ 7 other calls in file

3
4
5
6
7
8
9
10
11
12

const fs = require('fs')
const path = require('path')
const { EOL } = require('os')

const env = (e, def) => R.pathOr(def, ['env', e], process)

const log = (ref, off = env('LOG_OFF', false)) => {
  !off && console.log(typeof ref === 'object' ? JSON.stringify(ref) : ref)
  return ref
fork icon3
star icon44
watch icon6

+ 3 other calls in file

How does ramda.pathOr work?

ramda.pathOr is a function that allows you to retrieve the value at a given path of an object or an array, but it returns a default value if the path does not exist in the target object/array or if the target itself is null/undefined.

It takes three arguments: the default value to return if the path does not exist, the path itself as an array of strings or numbers, and the target object or array. It first uses the ramda.path function to try to retrieve the value at the specified path, and if that returns undefined or null, it returns the default value instead.

322
323
324
325
326
327
328
329
330
331
332
  });
};


exports.getNightsWithMinPrice = getNightsWithMinPrice;
var getMeta = (0, _reselect.createSelector)(searchByKey, R.propOr(EMPTY_OBJ, 'meta'));
var getOperatorsLinks = (0, _reselect.createSelector)(getMeta, R.pathOr(EMPTY_OBJ, ['links', 'operators']));
var getOperatorLink = (0, _reselect.createSelector)(getOperatorsLinks, function (_, _ref21) {
  var operatorID = _ref21.operatorID;
  return operatorID;
}, function (links, id) {
fork icon0
star icon3
watch icon0

+ 41 other calls in file

263
264
265
266
267
268
269
270
271
272
273
        "NOTTO, NHA", UPDATE_TEMPLATE_ID);
}


async function sendNotificationToEmergencyDetailsIfUpdated(profileFromReq, userData) {
    if (validateEmergencyMobileNumberUpdated(profileFromReq, userData)) {
        const notifyName = R.pathOr("", ["notificationDetails", "name"], profileFromReq);
        const notifyNumber = R.pathOr("", ["notificationDetails", "mobileNumber"], profileFromReq);
        await sendNotification(notifyNumber, `Dear Mr/Ms ${notifyName},\\n` +
            `This is to inform you that Mr/Ms ${profileFromReq.personalDetails.firstName} ${profileFromReq.personalDetails.middleName} ${profileFromReq.personalDetails.lastName} has pledged for Organ/Tissue donation.\\n` +
            "\\n" +
fork icon7
star icon1
watch icon0

+ 209 other calls in file

Ai Example

1
2
3
4
5
6
7
8
9
10
11
12
13
const R = require("ramda");

const data = {
  name: {
    first: "John",
    last: "Doe",
  },
  age: 25,
};

const firstName = R.pathOr("N/A", ["name", "first"], data); // 'John'
const lastName = R.pathOr("N/A", ["name", "last", "middle"], data); // 'N/A'
const middleName = R.pathOr("N/A", ["name", "middle"], data); // 'N/A'

In this example, pathOr is used to get the first name, last name middle name properties from an object named data. If the property does not exist, pathOr returns a default value specified as the first argument ('N/A' in this example).

74
75
76
77
78
79
80
81
82
83
84
85
86
      })
    ).join(EOL)}
}`
}


const fieldTypeConverter = (prop) => R.pathOr('undefined_type_error', ['type'], prop)


const convertType = (t) => R.or(typeConverter(t), t)


const generate = (message, schema, stringFormatter = scalars.stringFormatter) => {
fork icon3
star icon44
watch icon6

291
292
293
294
295
296
297
298
299
300

if (source.identifierType instanceof Object) {
  result.identifierType = {
    ...source.identifierType,
    id: ramda.pipe(
      ramda.pathOr(undefined, ['identifierType', 'id']),
      (id) => (id ? id.trim() : id)
    )(source),
  };
} else {
fork icon2
star icon13
watch icon8

+ 395 other calls in file

289
290
291
292
293
294
295
296
297
298
299
300
function mergeDeepRight$1 (obj1, obj2) {
  return R.mergeDeepRight(obj1, obj2)
}


function pathOr$1 (defaultValue, path, obj) {
  return R.pathOr(defaultValue, path, obj)
}


function propOr$1 (defaultValue, key, obj) {
  return R.propOr(defaultValue, key, obj)
fork icon2
star icon5
watch icon3

16
17
18
19
20
21
22
23
24
25

validate() {
    try {
        const { body } = this.request;
        const { email, password } = body;
        const deviceId = pathOr(undefined, ['device', 'deviceId'], body);
        if(email === undefined) {
            throw new HttpError(400, 'email can not be empty');
        }
        if(password === undefined) {
fork icon1
star icon0
watch icon0

+ 4 other calls in file

94
95
96
97
98
99
100
101
102
103
 *    the specified error's `"response.data.errors"` property (which is assumed
 *    to be a parsed object)
 */
function extractErrors(error) {
  return R.pipe(
    R.pathOr([], ["response", "data", "errors"]),
    R.unless(
      Array.isArray,
      R.pipe(
        R.prop("error"),
fork icon1
star icon0
watch icon0

+ 7 other calls in file

53
54
55
56
57
58
59
60
61
62
)

if (diff_ctxs.length == 0) {
	//protected multiple time dcr retain
	//each ctx can be only dcr once at most per event
	const prev_cur_retain = R.pathOr(0, [cur_name, 'retain'])(prev)
	const nex_cur_retain = R.pathOr(0, [cur_name, 'retain'])(nex)

	if (prev_cur_retain !== nex_cur_retain) {
		return nex
fork icon1
star icon0
watch icon0

+ 3 other calls in file

58
59
60
61
62
63
64
65
66
67
    pages: clone(pathOr([], ["project", "pagesOrder"], state))
  };
};
const getPagesToRestore = (state, action) => {
  return {
    activePage: pathOr("", ["project", "activePage"], state),
    pagesOrder: pathOr([], ["project", "pagesOrder"], state),
    pages: pathOr([], ["project", "pages"], state)
  };
};
fork icon0
star icon0
watch icon4

+ 473 other calls in file

206
207
208
209
210
211
212
213
214
215
216
  return pathOr(0, [props.type, "showAlert"], state.assets);
};


const getLoadingDeleteByType = (state, props) => {
  if (props.fromToolbar) {
    return pathOr(false, [props.type, "loadingDeleteToolbar"], state.assets);
  }
  return pathOr(false, [props.type, "loadingDelete"], state.assets);
};

fork icon0
star icon0
watch icon4

+ 31 other calls in file

3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
 * @param {Object} obj The object to retrieve the nested property from.
 * @return {*} The data at `path` of the supplied object or the default value.
 * @example
 *
 *      R.pathOr('N/A', ['a', 'b'], {a: {b: 2}}); //=> 2
 *      R.pathOr('N/A', ['a', 'b'], {c: {b: 2}}); //=> "N/A"
 */
var pathOr = _curry3(function pathOr(d, p, obj) {
    return defaultTo(d, path(p, obj));
});
fork icon0
star icon0
watch icon1

+ 37 other calls in file

63
64
65
66
67
68
69
70
71
72
  },
},
Unit: {
  unitId: R.path(['id']),
  unitName: R.pathOr('', ['label']),
  subtitle: R.pathOr('', ['label']),
  type: R.prop('label'),
  pricing: () => [],
  restrictions: R.propOr({}, 'restrictions'),
},
fork icon0
star icon0
watch icon0

55
56
57
58
59
60
61
62
63
64
    pluginObj.events.emit(`${this.name}.axios.error`, {
      request: args[0],
      err: errMsg,
    });
  }
  throw R.pathOr(err, ['response', 'data', 'error'], err);
});
this.tokenTemplate = () => ({
  sellerId: {
    type: 'text',
fork icon0
star icon0
watch icon0

+ 2 other calls in file

3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
 * @param {Array} p The path to use.
 * @param {Object} obj The object to retrieve the nested property from.
 * @return {*} The data at `path` of the supplied object or the default value.
 * @example
 *
 *      R.pathOr('N/A', ['a', 'b'], {a: {b: 2}}); //=> 2
 *      R.pathOr('N/A', ['a', 'b'], {c: {b: 2}}); //=> "N/A"
 */
var pathOr = _curry3(function pathOr(d, p, obj) {
    return defaultTo(d, path(p, obj));
fork icon0
star icon0
watch icon0

+ 35 other calls in file

80
81
82
83
84
85
86
87
88
89
90
91


  return state;
};


const getCompleteVariable = function(variable, configs) {
  const varType = pathOr(null, ["type"], variable);
  return mergeDeepRight(variable, {
    general: pathOr({}, ["general"], configs),
    specific: pathOr({}, [varType + "Cfg"], configs)
  });
fork icon0
star icon0
watch icon0

+ 11 other calls in file

7
8
9
10
11
12
13
14
15
16
17
const toError = when(complement(is(Error)), makeError)
const descriptionOrMessage = either(
    pick(['message', 'errors', 'data']),
    path(['props', 'description'])
)
const conditionOf = pathOr('', ['props', 'condition'])
const statusOf = propOr(500, 'code')


const releasable = (target, props) =>
    Object.assign(target, { props, conclude: (delivery) => delivery.release(props) })
fork icon0
star icon0
watch icon0

72
73
74
75
76
77
78
79
80
81
return promise.then(async () => {
  log('>>> Running batch number:', index + 1, `(size: ${batch.length})`);

  const values = await Promise.all(batch.map(fn => fn().catch(e => console.error(e))));

  const results = values.map(data => R.pathOr({ result: data }, ['cpanelresult', 'data', 0], data));
  const failed = results.filter(x => (x.result || {}).status != 1);

  log(`${values.length - failed.length}/${values.length}`);
  failed.length && log(JSON.stringify(failed, null, 2));
fork icon0
star icon0
watch icon0

69
70
71
72
73
74
75
76
77
78
79
    }, [])
}


const getResponseDataAtPath = (path, responseData, fields) => {
    if (path.length === 0) {
        const pathReponseData = R.pathOr({}, ["form", "schema"], responseData)
        return getDeficienciesFromAnswers(pathReponseData, responseData.moduleName, fields)
    } else {
        const truePath = ["subfolders", ...R.intersperse("subfolders", path), "form", "schema"]
        const trueModuleName = R.pathOr("", ["subfolders", ...R.intersperse("subfolders", path), "moduleName"], responseData)
fork icon0
star icon0
watch icon0

+ 5 other calls in file

Other functions in ramda

Sorted by popularity

function icon

ramda.clone is the most popular function in ramda (30311 examples)