简体   繁体   English

使用 ramda.js assocPath 为多个键分配特定值?

[英]Assign multiple keys a certain value using ramda.js assocPath?

I am quite new to JS and ramda.js.我对 JS 和 ramda.js 很陌生。 Let's say i have an object consisting of empty objects like this:假设我有一个 object 由这样的空对象组成:

obj = { 1: { }, 2: { }, 3: { } }

and array consisting of chosen keys of the obj .和由obj的选定键组成的数组。

arr = ['1', '2']

What i need is to create a certain key-value pair, for example a: 'value' , inside of the key objects chosen via arr , so the result would look like this:我需要的是在通过arr选择的键对象内创建一个特定的键值对,例如a: 'value' ,因此结果如下所示:

obj = { 
 1: { a: 'value' }, 
 2: { }, 
 3: { a: 'value' } 
}

I have tried to.map through the keys with我已经尝试通过键.map

arr.map(key => assocPath([key, 'a'], 'value', obj) )

, and also tried a way with arr.forEach() , but it doesn't work and i believe i may be missing some basic knowledge? ,并且还尝试了arr.forEach()的方法,但它不起作用,我相信我可能缺少一些基本知识? Or is there an alternative ramda.js function i should use?或者是否有我应该使用的替代 ramda.js function?

You should be able to do this with .forEach() :您应该可以使用.forEach()做到这一点:

arr.forEach(key => obj[key] = { a: 'value' });

The .map() function is for creating a new array from the elements of a source array, and you don't need to do that. .map() function 用于从源数组的元素创建新数组,您不需要这样做。

Take a look at my solution看看我的解决方案

 const object = { 1: { }, 2: { }, 3: { } } const array = ['1', '3'] function magic(obj, arr) { return arr.reduce((acc, key) => ({...acc, [key]: { a: 'value' }, }), obj) } console.log(magic(object, array))

This is also can be achieved with ramda's functions这也可以通过 ramda 的功能来实现

 const object = { 1: { }, 2: { }, 3: { } } const array = ['1', '3'] const magicR = R.reduce((acc, key) => R.assocPath([ key, 'a' ], 'value', acc)) console.log(magicR(object, array))
 <script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.26.1/ramda.min.js"></script>

Ramda methods are immutable - they don't mutate the original object, but return a new one. Ramda 方法是不可变的——它们不会改变原来的 object,而是返回一个新的。 The R.assocPath method is no different in this regard. R.assocPath 方法在这方面没有什么不同。 To update the object, you'll need to iterate the array with R.reduce, use R.assocPath, get a new object, etc... To update the object, you'll need to iterate the array with R.reduce, use R.assocPath, get a new object, etc...

 const { reduce, assocPath } = R const fn = reduce((o, key) => assocPath([key, 'a'], 'value', o)) const obj = { 1: { }, 2: { }, 3: { } } const arr = ['1', '2'] const result = fn(obj)(arr) console.log(result)
 <script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.26.1/ramda.js"></script>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM