0

We have a json array that has the form:

[
{id: 123, name: 'abc', symbol: 'xyz'},
{id: 456, name: 'def', symbol: null},
...
]

We are looking for a Ramda transformation that will replace all instances where the 'symbol' property is NULL, with a simple '' (empty string). Any ideas about how this can be done without getting into a forEach or for...next loop?

1
  • The answer from @Tomalak captures exactly what you need. But the general "without getting into a forEach or for...next loop" can generally be answered pretty straightforwardly. Here, what would you want to do in your loop? You want to transform each value into one without a null symbol. Boom! map. If instead you said, I want to find only those..., you know you'll likely want to filter. If you wanted to find the first one that matches, then find. If you want to combine them all into a single smooshed object, then reduce. That will cover a great majority of your looping needs. Commented Nov 17, 2017 at 19:14

3 Answers 3

2

const data = [
  {id: 123, name: 'abc', symbol: 'xyz'},
  {id: 456, name: 'def', symbol: null},
  // ...
];

const newData = R.map(R.over(R.lensProp('symbol'), R.defaultTo('')), data);

console.log(newData);
<script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.25.0/ramda.min.js"></script>

Sign up to request clarification or add additional context in comments.

2 Comments

Marking this as correct answer since it seems the most complete from a "functional" perspective. As well it allows me to hit other individual properties without having to address others I'm not concerned with. However the answers from 김재원 and mac also worked - thanks for the ideas!
@Gatmando You can always define something like const defaultPropTo = (prop, def) => R.over(R.lensProp(prop), R.defaultTo(def)) and then simply R.map(defaultPropTo('symbol', ''), data).
1

How about this?

R.map(({ symbol, ...otherProps }) => ({ ...otherProps, symbol: symbol || '' }))(arr);

Comments

1

You can use lensProp with set.

arr.map(o => R.set(R.lensProp('symbol'), o.symbol || '', o))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.