or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

tessl/npm-lodash.matches

A utility function from lodash that creates a predicate function which compares properties of the given object with the corresponding property values of source, returning true if all the property values are equivalent, else false

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
npmpkg:npm/lodash@3.1.x

To install, run

npx @tessl/cli install tessl/npm-lodash.matches@3.1.0

0

# Lodash Matches

1

2

Lodash matches is a utility function that creates a predicate function for deep object comparison. It takes a source object as input and returns a function that tests whether other objects contain all the key-value pairs present in the source object, using deep equality comparison.

3

4

## Package Information

5

6

- **Package Name**: lodash

7

- **Package Type**: npm

8

- **Language**: JavaScript

9

- **Installation**: `npm install lodash`

10

- **Specific Function**: `matches` (from lodash v3.1.0)

11

12

## Core Imports

13

14

CommonJS (primary method for v3.1.0):

15

16

```javascript

17

const _ = require("lodash");

18

const matches = _.matches;

19

```

20

21

Global usage (browser):

22

23

```javascript

24

const matches = _.matches;

25

```

26

27

AMD usage:

28

29

```javascript

30

define(['lodash'], function(_) {

31

const matches = _.matches;

32

});

33

```

34

35

## Basic Usage

36

37

```javascript

38

const _ = require("lodash");

39

40

// Create sample data

41

const users = [

42

{ user: 'fred', age: 40 },

43

{ user: 'barney', age: 36 }

44

];

45

46

// Create a matcher function

47

const matchesAge = _.matches({ age: 36 });

48

49

// Use with collection methods

50

const result = _.filter(users, matchesAge);

51

// => [{ user: 'barney', age: 36 }]

52

53

const found = _.find(users, matchesAge);

54

// => { user: 'barney', age: 36 }

55

```

56

57

## Capabilities

58

59

### Matches Function

60

61

Creates a function that performs deep comparison between objects and the provided source pattern.

62

63

```javascript { .api }

64

/**

65

* Creates a function which performs a deep comparison between a given object

66

* and `source`, returning `true` if the given object has equivalent property

67

* values, else `false`.

68

*

69

* @static

70

* @memberOf _

71

* @category Utility

72

* @param {Object} source - The object of property values to match

73

* @returns {Function} Returns the new predicate function

74

*/

75

function matches(source);

76

```

77

78

The returned predicate function signature:

79

80

```javascript { .api }

81

/**

82

* @param {Object} object - The object to inspect

83

* @returns {boolean} Returns `true` if object matches, else `false`

84

*/

85

function predicate(object);

86

```

87

88

**Usage Examples:**

89

90

```javascript

91

const _ = require("lodash");

92

93

// Simple property matching

94

const matchName = _.matches({ name: 'fred' });

95

matchName({ name: 'fred', age: 40 }); // => true

96

matchName({ name: 'barney', age: 36 }); // => false

97

98

// Multiple property matching

99

const matchMultiple = _.matches({ age: 36, active: true });

100

matchMultiple({ name: 'barney', age: 36, active: true }); // => true

101

matchMultiple({ name: 'fred', age: 40, active: true }); // => false

102

103

// Deep object matching

104

const user = {

105

profile: {

106

name: 'fred',

107

settings: { theme: 'dark' }

108

},

109

status: 'active'

110

};

111

112

const matchNested = _.matches({

113

profile: {

114

settings: { theme: 'dark' }

115

}

116

});

117

matchNested(user); // => true

118

119

// Array and mixed type matching

120

const matchComplex = _.matches({

121

tags: ['javascript', 'lodash'],

122

metadata: { version: 1 }

123

});

124

125

matchComplex({

126

name: 'project',

127

tags: ['javascript', 'lodash'],

128

metadata: { version: 1, created: '2023-01-01' }

129

}); // => true

130

```

131

132

### Key Characteristics

133

134

- **Deep Comparison**: Performs recursive equality checks on nested objects and arrays

135

- **Partial Matching**: Only requires that the target object contains all properties from the source (additional properties in target are ignored)

136

- **SameValueZero Equality**: Uses SameValueZero comparison algorithm (like `===`, but `NaN` equals `NaN`)

137

- **Immutable Source**: The source object is deep cloned internally, so modifications to the original source don't affect the matcher

138

- **Type Flexibility**: Works with primitives, objects, arrays, and mixed data structures

139

140

### Common Use Cases

141

142

```javascript

143

const _ = require("lodash");

144

145

const products = [

146

{ name: 'laptop', category: 'electronics', price: 999, inStock: true },

147

{ name: 'book', category: 'media', price: 29, inStock: false },

148

{ name: 'phone', category: 'electronics', price: 599, inStock: true }

149

];

150

151

// Filter by category

152

const electronics = _.filter(products, _.matches({ category: 'electronics' }));

153

154

// Find available electronics

155

const availableElectronics = _.filter(products, _.matches({

156

category: 'electronics',

157

inStock: true

158

}));

159

160

// Check if any products match criteria

161

const hasAffordableElectronics = _.some(products, _.matches({

162

category: 'electronics',

163

price: 599

164

}));

165

166

// Use with array methods

167

const matchElectronics = _.matches({ category: 'electronics' });

168

const electronicsArray = products.filter(matchElectronics);

169

```

170

171

### Edge Cases and Behavior

172

173

```javascript

174

const _ = require("lodash");

175

176

// Empty source object matches everything

177

const matchAll = _.matches({});

178

matchAll({ anything: 'here' }); // => true

179

matchAll({}); // => true

180

181

// NaN handling (SameValueZero comparison)

182

const matchNaN = _.matches({ value: NaN });

183

matchNaN({ value: NaN }); // => true (unlike === comparison)

184

185

// Null and undefined handling

186

const matchNull = _.matches({ value: null });

187

matchNull({ value: null }); // => true

188

matchNull({ value: undefined }); // => false

189

matchNull({}); // => false (missing property)

190

191

// Array matching requires exact order and values

192

const matchArray = _.matches({ items: [1, 2, 3] });

193

matchArray({ items: [1, 2, 3] }); // => true

194

matchArray({ items: [3, 2, 1] }); // => false (different order)

195

matchArray({ items: [1, 2, 3, 4] }); // => false (different length)

196

197

// Empty arrays and objects in source match any arrays/objects in target

198

const matchEmpty = _.matches({ items: [], config: {} });

199

matchEmpty({ items: [1, 2, 3], config: { theme: 'dark' } }); // => true

200

matchEmpty({ items: [], config: {} }); // => true

201

202

// Deep nested object matching

203

const matchDeep = _.matches({

204

user: {

205

profile: {

206

settings: { notifications: true }

207

}

208

}

209

});

210

211

matchDeep({

212

user: {

213

name: 'alice',

214

profile: {

215

age: 30,

216

settings: {

217

notifications: true,

218

theme: 'dark'

219

}

220

}

221

}

222

}); // => true (contains required nested structure)

223

```

224

225

## Error Handling

226

227

The `matches` function itself does not throw errors under normal usage. The returned predicate function handles:

228

229

- **Null/undefined objects**: Returns `false` when the object to test is `null` or `undefined`

230

- **Missing properties**: Returns `false` when required properties are missing

231

- **Type mismatches**: Returns `false` when property values don't match using SameValueZero comparison

232

233

```javascript

234

const _ = require("lodash");

235

236

const matcher = _.matches({ name: 'fred' });

237

238

matcher(null); // => false

239

matcher(undefined); // => false

240

matcher({}); // => false (missing name property)

241

matcher({ name: 'fred' }); // => true

242

```

243

244

## Related Functions

245

246

While this K-tile focuses on `_.matches`, Lodash v3.1.0 includes related functions that work with similar matching logic:

247

248

- **`_.where(collection, source)`**: Filters a collection using the same deep comparison logic as `matches`

249

- **`_.isMatch(object, source)`**: Performs direct object comparison without creating a predicate function

250

- **`_.findWhere(collection, source)`**: Finds the first element that matches the source object

251

252

These functions use the same underlying matching algorithm and complement `_.matches` in collection operations.