简体   繁体   中英

How to push items from an array to another array using ramda expressions?

I have a small problem, I have an array of children, I parse it, I get data from it and reformat it and push it into another array subMenuContent , it is working fine, but I need to clean my code a little bit better, I am using ramda as a library to simplify things for me.

Here is what I was doing before, simple javascript.

    let subMenuContent = [];

    for (let counter = 0; counter < children.length; counter++) {
      let parent = children[counter].props.item.id;
      let childs = children[counter].props.item.childrens;
      for (let i = 0; i < childs.length; i++) {
        let child = {
          content: childs[i],
          class: 'cdiscountLinks cdiscountChip-' + childs[i].id + '-' + parent,
        };
        subMenuContent.push(child);
      }
    }

What I am trying to do now is:

    const subMenuContents = map(function(item){
      let parent = item.props.item.id;
      let childs = item.props.item.childrens;
      const itemChilds = map(function(child){
        let childItem = {
          content: child,
          class: 'cdiscountLinks cdiscountChip-' + child.id + '-' + parent,
        }
        return childItem;
      }, childs)
      return itemChilds;

    },children)

EDIT: Now I used this

    const subMenuContents = pipe(
      map(function(item) {
        let parent = item.props.item.id;
        let childs = item.props.item.childrens;
        const itemChilds = map(function(child) {
          let childItem = {
            content: child,
            class: 'cdiscountLinks cdiscountChip-' + child.id + '-' + parent,
          };
          return childItem;
        }, childs);
        return itemChilds;
      }, children),
      flatten,
    )(subMenuContents);

But I get an error:

f.apply is not a function

What am I doing wrong? Any help would be much appreciated.

You might be interested in looking at the R.chain function in Ramda. This is sometimes known as flatMap , because it can be thought of mapping over the data type and then flattening the nested result.

R.chain can work with many different data types, though for arrays it effectively maps over each element of the array to produce an array for each then concatenates them all together.

In your example, you will want to look at replacing your outermost const subMenuContents = map(...) with const subMenuContents = chain(...) .

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