Leon Gaban Leon Gaban - 1 month ago 9
Javascript Question

How to convert this _.each function that adds a key to each object into Ramda?

http://jsfiddle.net/leongaban/4xfc4g3c/1/

Lodash

const spamData = [true, true, false];
const tweets = [{ tweet: "Hello" }, { tweet: "World" }, { tweet: "Pork"}];

_.each(spamData, (value, i) => {
tweets[i]['spam'] = value;
});

log(tweets);





Stuck at this point:

Ramda

const setSpamValues = (spamValue) => {
return spamValue;
};

R.forEach(setSpamValues, spamData);


Not sure what would be the best approach to now sent the returned
spamValue
to a new key named
spam
for each tweet.

Answer

You might want to reconsider you use of Rambda if you're struggling with this elementary problem.

You should be in the habit of thinking about how to solve these problems on your own. Once you understand the utility provided by Rambda, maybe then it makes sense to use it.

Here is the result you're looking for using nothing other than plain-old JavaScript.

const spamData = [true, true, false];
const tweets   = [{ tweet: "Hello" }, { tweet: "World" }, { tweet: "Pork"}];

let result = tweets.map((t,i) =>
  Object.assign({}, t, {spam: spamData[i]})
);

console.log(result);
// [
//   {"spam": true, "tweet": "Hello"},
//   {"spam": true, "tweet": "World"},
//   {"spam": false, "tweet": "Pork"}
// ]


If you insist on using Rambda, you're probably looking for R.zip

const spamData = [true, true, false];
const tweets   = [{ tweet: "Hello" }, { tweet: "World" }, { tweet: "Pork"}];

let result = R.zip(spamData, tweets).map(([spam, tweet]) =>
  Object.assign({}, tweet, {spam})
);

console.log(result);
// [
//   {"spam": true, "tweet": "Hello"},
//   {"spam": true, "tweet": "World"},
//   {"spam": false, "tweet": "Pork"}
// ]
<script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.22.1/ramda.js"></script>

ps, next time you ask a question you should include the expected output.


Comments