How to use the assoc function from ramda

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

ramda.assoc is a function that creates a new object with a modified property using a given key-value pair, without mutating the original object.

33
34
35
36
37
38
39
40
41
42

if (requesterId === osmId) {
  const allIds = orgKeys.map(prop('id'))
  const allValues = pick(allIds, tags)
  const keysToSend = orgKeys.map((key) => {
    return assoc('value', allValues[key.id], key)
  })
  return reply.send(keysToSend)
} else {
  requesterIsMemberOfOrg = await org.isMember(orgId, requesterId)
fork icon4
star icon23
watch icon24

+ 7 other calls in file

117
118
119
120
121
122
123
124
125
126
R.compose(
  R.dissoc('data'),
  R.over(
    R.lens(
      coerceDataToApiDescriptions,
      R.assoc('apiDescriptions')
    ),
    R.identity
  )
)
fork icon303
star icon0
watch icon2

How does ramda.assoc work?

ramda.assoc is a function that takes three arguments: a property key, a value, and an object. It returns a new object with the property specified by the key set to the new value. If the key already exists in the object, its value is replaced; otherwise, a new key-value pair is added. Unlike JavaScript's native Object.assign() method, ramda.assoc does not mutate the original object, but instead returns a new object with the modified property. This makes it a pure function, which is a key concept in functional programming. The syntax for using ramda.assoc is: scss Copy code {{{{{{{ class="!whitespace-pre hljs language-scss">ramda.assoc(key, value, obj) Where: key: A string or symbol representing the key of the property to be modified or added. value: The new value for the property. obj: The object that contains the property to be modified or to which a new property will be added. The function returns a new object with the modified or added property. Example: javascript Copy code {{{{{{{ const R = require('ramda'); const user = {name: 'Alice', age: 30}; const newUser = R.assoc('age', 31, user); console.log(user); // {name: 'Alice', age: 30} console.log(newUser); // {name: 'Alice', age: 31} In this example, we use ramda.assoc to create a new object newUser with the same properties as the original object user, except that the age property is set to a new value of 31. The original user object is not modified, and a new object is returned with the updated property.

41
42
43
44
45
46
47
48
49
50

// Update

// action -> model -> newModel
const update = Action.caseOn({
  ChangeNewTitle: R.assoc('newTitle'),
  Create: (model) => R.evolve({todos: R.append(Todo.init(model.nextId, model.newTitle)),
                               nextId: R.inc,
                               newTitle: R.always('')}, model),
  Remove: (todo, model) => R.evolve({todos: R.reject(R.eq(todo))}, model),
fork icon92
star icon0
watch icon2

+ 3 other calls in file

27
28
29
30
31
32
33
34
35
36
37
38
      R.lensPath(amountBuyPath),
      reduceBySlippage(slippage)
    )
  )(orders)


  const appliedData = R.assoc('orders', ordersPostSlippage)(validatedData)


  return appliedData
}

fork icon21
star icon22
watch icon0

Ai Example

1
2
3
4
5
6
7
const R = require("ramda");

const user = { name: "Alice", age: 30 };
const newUser = R.assoc("age", 31, user);

console.log(user); // {name: 'Alice', age: 30}
console.log(newUser); // {name: 'Alice', age: 31}

In this example, we use ramda.assoc to create a new object newUser with the same properties as the original object user, except that the age property is set to a new value of 31. The original user object is not modified, and a new object is returned with the updated property.

11
12
13
14
15
16
17
18
19
20
willSendRequest(_path, request) {
  const { jwtdata } = this.context.state ?? {}
  <%_ if(withMultiTenancy){ _%>
  request.headers = assoc(TenantId, jwtdata?.tid, request.headers)
  <%_}_%>
  request.headers = assoc(UserPassport, jwtdata ? JSON.stringify(jwtdata) : undefined, request.headers)
  request.headers = assoc(UserId, jwtdata?.sub, request.headers)

  //TODO to be removed
  if (this.context.token) {
fork icon3
star icon26
watch icon8

+ 935 other calls in file

7
8
9
10
11
12
13
14
15
16
17
const addStyleLintPluginToPostCSSLoaders = path => config =>
  edit(
    subConfig => {
      const { plugins } = subConfig


      return assoc('plugins', () => [styleLint({ configFile: path }), ...plugins()], subConfig)
    },
    getPaths(isPostCSSOptions, config),
    config
  )
fork icon2
star icon5
watch icon0

5
6
7
8
9
10
11
12
13
14
15
16
17


module.exports = (logger) => (config) => {
  logger.info('Starting migration ...');


  const migrationConfigs = [].concat(config.migrations);
  const getOptions = R.assoc('connection', config);


  const migrate = (migrationConfig) => {
    const options = R.clone(getOptions(migrationConfig));
    options.connection.user = config.migrationsUser || config.user;
fork icon1
star icon6
watch icon0

15
16
17
18
19
20
21
22
23
24

const readFile = R.partialRight(fs.readFileSync, [{ encoding: 'utf-8' }]);

const shortName = name => path.basename(name, SQL_EXT);

const nameToContent = (acc, name) => R.assoc(shortName(name), R.trim(readFile(name)), acc);

const loadSql = (location) => {
  const files = fs.readdirSync(location);
  const load = R.pipe(
fork icon1
star icon6
watch icon0

+ 3 other calls in file

410
411
412
413
414
415
416
417
418
419
const createTokensFan = async (otApiKey, otSecret, stageSessionId, sessionId) => {
  const options = {
    role: OpenTok.otRoles.PUBLISHER,
    data: buildOtData(roles.FAN)
  };
  const backstageToken = await OpenTok.createToken(otApiKey, otSecret, sessionId, R.assoc('data', buildOtData(roles.BACKSTAGE_FAN), options));
  const stageToken = await OpenTok.createToken(otApiKey, otSecret, stageSessionId, options);
  return {
    backstageToken,
    stageToken
fork icon12
star icon5
watch icon0

152
153
154
155
156
157
158
159
160
161

function interpretPure(free, store) {
  return free.resume().either(function(kvs) {
    return kvs.cata({
      Put: function(key, val, next) {
        return interpretPure(next, R.assoc(key, val, store));
      },
      Del: function(key, next) {
        return interpretPure(next, R.dissoc(key, store));
      },
fork icon1
star icon5
watch icon4

+ 7 other calls in file

105
106
107
108
109
110
111
112
113
114
return kvs.cata({
  Get: function(str, cont) {
    return pureObject(cont(store[str]), store);
  },
  Put: function(str, val, cont) {
    return pureObject(cont, R.assoc(str, val, store));
  },
  Del: function(str, cont) {
    return pureObject(cont, R.dissoc(str, store));
  },
fork icon0
star icon4
watch icon2

11
12
13
14
15
16
17
18
19
20
    ...state,
    ...newEvents
  };
case "ADD_EVENT":
case "UPDATE_EVENT":
  return R.assoc(action.doc._id, action.doc, state);
case "REMOVE_EVENT":
  return R.dissoc(action.doc._id, state);
case "LOGIN":
case "LOGOUT":
fork icon2
star icon0
watch icon0

151
152
153
154
155
156
157
158
159
160
161
        nationality: 'Spanish',
        married: true
    }
    console.log("object keys =", _.keys(obj))
    console.log("object values =", _.values(obj))
    console.log("object add attribute =", _.assoc('height', 1.68, obj))
    console.log("object remove attribute =", _.dissoc('nationality', obj))
    console.log("object check attribute =", _.has('married', obj))


}
fork icon1
star icon2
watch icon0

216
217
218
219
220
221
222
223
224
225
226
227
228
  })


  const table = getTableForProfileType(profileType)


  return conn(table)
    .update({ profile: assoc('tags', tags, currentProfile), updated_at: conn.fn.now() })
    .where('id', id)
}


/**
fork icon0
star icon1
watch icon0

47
48
49
50
51
52
53
54
55
56
57
58
59


  // remove properties object. maybe change this if we want to keep styling later
  R.map(R.assoc("properties", {})),


  // nest into object
  R.assoc('features', R.__, { type: 'FeatureCollection' }),


  // strigify that shit
  R.toString,
)(files)
fork icon1
star icon0
watch icon0

587
588
589
590
591
592
593
594
595
596
R.when(R.prop("scroll"), R.omit(["pageNum"])),
R.when(R.prop("temporal"), (params) =>
  // Replace all occurences of `now` in temporal with the current date/time.
  // Passing `Date.now()` to the `Date` constructor is not necessary, but
  // doing so allows us to mock a value during unit testing.
  R.assoc(
    "temporal",
    params.temporal.replace(/now/gi, new Date(Date.now()).toISOString()),
    params,
  )
fork icon1
star icon0
watch icon0

289
290
291
292
293
294
295
296
297
298
// replaced with a value rounded to 3 significant figures
const rungSpecsCapMaxBitrate = parametricLadder =>
  topRungSpec(parametricLadder).bitrate > parametricLadder.limits.finalBitrateMax ?
    rungSpecsReplace(
      R.map(
        r => R.assoc(
          'bitrate',
          r.bitrate * parametricLadder.limits.finalBitrateMax / topRungSpec(parametricLadder).bitrate,
          r
        )
fork icon0
star icon0
watch icon0

+ 758 other calls in file

70
71
72
73
74
75
76
77
78
79
    } else {
      const lengthScore = calc.iScore(1, MAX_KEYWORD_LENGTH, lengthStats.length);
      const indexScore = calc.izScore(4, lengthStats.index);
      score = calc.aggregate([10, 1], [lengthScore, indexScore]);
    }
    return R.assoc('score', score, lengthStats);
  }),

getCollection,
getGenre,
fork icon0
star icon0
watch icon1

+ 330 other calls in file

88
89
90
91
92
93
94
95
96
97
        ranked,
        installs: store.getInstallsScore(topApps),
        length: getKeywordLength(keyword)
      };
    })
    .then((stats) => R.assoc('score', getScore(stats), stats)));
}


module.exports = build;
fork icon0
star icon0
watch icon1

+ 661 other calls in file

80
81
82
83
84
85
86
87
88
89
    ]))
    .then((scores) => ({
      keywords: scores[0],
      collections: scores[1]
    }))
    .then((stats) => R.assoc('score', getVisbilityScore(stats), stats));
}


module.exports = build;
fork icon0
star icon0
watch icon1

+ 270 other calls in file

Other functions in ramda

Sorted by popularity

function icon

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