Remove list of keys in object, the key may not exist - ramda.js

I have a object that may have some keys
const input = {
whatsapp: "123",
telegram: "bbb",
}
And I want to remove a list of possible keys:
const removeThis = ['whatsapp', 'telegram', 'signal', 'wechat']
Using Ramda, how can I remove all possible keys in the object input?
The key may not exist in the object.

You can use R.omit:
const input = {
whatsapp: "123",
telegram: "bbb",
stay: 'xxx'
}
const removeThis = ['whatsapp', 'telegram', 'signal', 'wechat']
const result = R.omit(removeThis, input)
console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.27.1/ramda.js" integrity="sha512-3sdB9mAxNh2MIo6YkY05uY1qjkywAlDfCf5u1cSotv6k9CZUSyHVf4BJSpTYgla+YHLaHG8LUpqV7MHctlYzlw==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>

Related

Pick fields from an object and return one field as an array

Using Ramda, I am trying to achieve something like this:
let data = {
'accountNumber' : '12345',
'holderName' : 'XYZ',
'id' : '12XX',
'type' : 'savings',
...rest
}
let newObj = R.pick(['accountNumber', 'id', 'type']) (data);
output -> newObj = {
'accountNumber' : '12345',
'id' : '12XX',
'type' : 'savings'
}
I want result like this:
newObj = {
'accountNumbers' : ['12345'],
'id' : '12XX',
'type' : 'savings'
}
I want accountNumber field to be put inside an array of accountNumbers.
I understand pick won't work in this case but I am not able to achieve it through Ramda. It can be done easily using JavaScript but is it possible to achieve via Ramda?
You can pick the properties, and create a new object with changed keys using R.applySpec():
const { applySpec, pipe, of, prop } = R
const fn = applySpec({
accountNumbers: pipe(prop('accountNumber'), of),
holderName: prop('holderName'),
id: prop('id')
})
const data = {
'accountNumber': '12345',
'holderName': 'XYZ',
'id': '12XX',
'type': 'savings',
}
const result = fn(data)
console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.28.0/ramda.min.js" integrity="sha512-t0vPcE8ynwIFovsylwUuLPIbdhDj6fav2prN9fEu/VYBupsmrmk9x43Hvnt+Mgn2h5YPSJOk7PMo9zIeGedD1A==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
Another option is to add accountNumbers using R.applySpec (based on this answer), and then pick the properties, including the updated one from the object:
const { pipe, applySpec, chain, mergeLeft, prop, of, pick } = R
const updateObject = pipe(applySpec, chain(mergeLeft))
const addAccountNumbers = updateObject({
accountNumbers: pipe(prop('accountNumber'), of)
})
const fn = pipe(addAccountNumbers, pick(['accountNumbers', 'holderName', 'id']))
const data = {
'accountNumber': '12345',
'holderName': 'XYZ',
'id': '12XX',
'type': 'savings',
}
const result = fn(data)
console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.28.0/ramda.min.js" integrity="sha512-t0vPcE8ynwIFovsylwUuLPIbdhDj6fav2prN9fEu/VYBupsmrmk9x43Hvnt+Mgn2h5YPSJOk7PMo9zIeGedD1A==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>

Ramda - get ids from nested array of multiple objects

I am trying to get outgoingNodes IDs which are stored in array which is inside objects like in example below but I have no idea where to start...:
const nodes = {
"818": {
"id": "818",
"index": 1,
"outgoingNodes": [
"819"
],
},
"819": {
"id": "819",
"outgoingNodes": [
"820",
"821"
],
}
}
I would like to get an array of IDs as a result. Any help will be appreciated.
Get the values (sub objects), pluck the outgoingNodes arrays, and flatten to a single array:
const { pipe, values, pluck, flatten } = R
const fn = pipe(
values,
pluck('outgoingNodes'),
flatten
)
const nodes = {"818":{"id":"818","index":1,"outgoingNodes":["819"]},"819":{"id":"819","outgoingNodes":["820","821"]}}
const result = fn(nodes)
console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.27.1/ramda.min.js" integrity="sha512-rZHvUXcc1zWKsxm7rJ8lVQuIr1oOmm7cShlvpV0gWf0RvbcJN6x96al/Rp2L2BI4a4ZkT2/YfVe/8YvB2UHzQw==" crossorigin="anonymous"></script>
Another option is to combine getting the outgoingNodes arrays, and flattening to a single array using R.chain with R.prop:
const { pipe, values, chain, prop } = R
const fn = pipe(
values,
chain(prop('outgoingNodes')),
)
const nodes = {"818":{"id":"818","index":1,"outgoingNodes":["819"]},"819":{"id":"819","outgoingNodes":["820","821"]}}
const result = fn(nodes)
console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.27.1/ramda.min.js" integrity="sha512-rZHvUXcc1zWKsxm7rJ8lVQuIr1oOmm7cShlvpV0gWf0RvbcJN6x96al/Rp2L2BI4a4ZkT2/YfVe/8YvB2UHzQw==" crossorigin="anonymous"></script>

Lodash: filter when I have nested array property?

Consider below example. I am using Lodash
"home":[
{
"data":{
"interests":["sports", "travel", "boxing"],
"city":["x", "y", "z"],
"name":"test1"
},
"count":["1", "2"],
"country":"CA"
},
{
"data":{
"interests":["painting", "travel", "dancing"],
"city":["a", "y", "b"],
"name":"test2"
},
"count":["1","3"],
"country":"US"
}
]
If I'll try the function on key value pair example :
_.find(home, ['data.country', 'US']); // It is returning me the 2nd object
requirement :
I want all the objects where data.interests is 'dancing'.
Tried :
_.find(home, ['data.interests', 'dancing']) // It is returning []
I have also tried filter(), where() and map but unable to get the complete object.
Thanks in advance.
You can use vanilla JS or lodash funcntions - Filter the array, and for each item check if the data.interests array includes the requested word.
Vanilla:
const home = [{"data":{"interests":["sports","travel","boxing"],"city":["x","y","z"],"name":"test1"},"count":["1","2"],"country":"CA"},{"data":{"interests":["painting","travel","dancing"],"city":["a","y","b"],"name":"test2"},"count":["1","3"],"country":"US"}]
const result = home.filter(o => o.data.interests.includes('dancing'))
console.log(result)
Lodash:
const home = [{"data":{"interests":["sports","travel","boxing"],"city":["x","y","z"],"name":"test1"},"count":["1","2"],"country":"CA"},{"data":{"interests":["painting","travel","dancing"],"city":["a","y","b"],"name":"test2"},"count":["1","3"],"country":"US"}]
const result = _.filter(home, o => _.includes(o.data.interests, 'dancing'))
console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.js"></script>

Replace value of key using ramda.js

I have the following array of objects:
const originalArray = [
{name: 'name1', value: 10},
{name: 'name2', value: 20}
]
And the following object
names = {
name1: 'generic_name_1',
name2: 'generic_name_2'
}
I would like the first array to be transformed like this:
[
{name: 'generic_name_1', value: 10},
{name: 'generic_name_2', value: 20}
]
What I have tried so far:
const replaceName = (names, obj) => {
if(obj['name'] in names){
obj['name'] = names[obj['name']];
}
return obj;
}
const modifiedArray = R.map(replaceName(names), originalArray)
Is there a more ramda-ish way to do this?
Using native JS inside Ramda functions is not unramdaish. The only problem in your code is that you mutate the original object - obj['name'] = names[obj['name']];.
I would use R.when to check if the name exists in the names object, and if it does evolve the object to the new name. If it doesn't the original object would be returned.
const { flip, has, prop, map, when, pipe, evolve } = R
const hasProp = flip(has)
const getProp = flip(prop)
const fn = names => map(when(
pipe(prop('name'), hasProp(names)),
evolve({
name: getProp(names)
})
))
const originalArray = [{"name":"name1","value":10},{"name":"name2","value":20},{"name":"name3","value":30}]
const names = {"name1":"generic_name_1","name2":"generic_name_2"}
const result = fn(names)(originalArray)
console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.27.0/ramda.js"></script>
I wouldn't use any Ramda functions for this. I would simply avoid mutating the original, perhaps with code like this:
const transform = (names) => (arr) => arr .map (
({name, ... rest}) => ({name: names [name] || name, ... rest})
)
const originalArray = [{name: 'name1', value: 10},{name: 'name2', value: 20}]
const names = {name1: 'generic_name_1',name2: 'generic_name_2'}
console .log (
transform (names) (originalArray)
)

Using ramda to modify data in array

Input:
[
{
temp: "24",
date: "2019-10-16T11:00:00.000Z"
}
]
Output:
[[new date("2019-10-16T11:00:00.000Z").getTime(), 24]]
Got some annoying mutability problems if I do it in vanilla javascript.
Good case to use ramda.
Something like:
const convertFunc = ...
const convertArr = R.map(convertFunc)
const result = convertArr(arr);
I'm stuck. Any ideas what Ramda functions to use?
I'm not sure Ramda would add anything substantial. Especially if you can use parameter destructuring:
map(({temp, date}) => [new Date(date).getTime(), temp],
[{ temp: "24",
date: "2019-10-16T11:00:00.000Z"}]);
//=> [[1571223600000, "24"]]
You can map the array of objects, and use R.evolve to convert the date string to time via Date.parse(), and then get the R.props to convert to an array of arrays.
const { map, pipe, evolve, identity, props } = R
const fn = map(pipe(
evolve({ temp: identity, date: Date.parse }),
props(['date', 'temp'])
))
const data = [{temp: "24",date: "2019-10-16T11:00:00.000Z"}]
const result = fn(data)
console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.26.1/ramda.js"></script>