简体   繁体   中英

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.

您也可以使用R.zipWithR.assoc实现此目的。

const updatedTweets = R.zipWith(R.assoc('spam'), spamData, tweets);

You should be in the habit of thinking about how to solve these problems on your own before leveraging on library to do it for you. If you're struggling with this elementary problem, you might want to reconsider your use of Ramda altogether. Once you understand the utility provided by Ramda, 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 Ramda, 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.


The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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