markdown Ramda map和mapObjIndexed

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了markdown Ramda map和mapObjIndexed相关的知识,希望对你有一定的参考价值。

**Basic Example:**
<pre><code>const double = x => x * 2;
R.map(double, [1, 2, 3]); //=> [2, 4, 6]
R.map(double, {x: 1, y: 2, z: 3}); //=> {x: 2, y: 4, z: 6}</code></pre>


**Intermediate Example:**
<pre><code>
const person = {
    "person": {
      "id": "1",
      "name": "John Doe",
      "hours": {
        "edges": [
          {
            "node": {
              "id": "1",
              "number": 8
            }
          },
          {
            "node": {
              "id": "2",
              "number": 7
            }
          }
        ]
      }
    }
};

// This function extracts the of number hours from a contact ands maps it into an array
function monthlyWorked(data) {
  const setHour = (hour) => hour.node.number;
  const hours = R.map(setHour, data.person.hours.edges);
  return hours;
}

console.log(monthlyWorked(person)); // [8,7]
</pre></code>

**Advanced Example:**

<pre><code>
const contact = {
    "contact": {
      "id": 1,
      "name": "Name",
      "keywords": {
        "edges": [
          {
            "node": {
              "id": "1",
              "keyName": "Key1"
            }
          },
          {
            "node": {
              "id": "2",
              "keyName": "Key2"
            }
          }
        ]
      }
    }
}

function getKeywords(keywords) { 
  const keywordsEdges = R.propOr([], 'edges', keywords,); // Sets an empty array on edges of keywords that are empty
  return R.pluck('node', keywordsEdges); // Removes the node property from keywords
}

function formatContact(data) {
  const setContact = (value, key) => key === 'keywords' ? R.pluck('id', getKeywords(value)) : value;
  const formattedContacts = R.mapObjIndexed(setContact, data.contact);
  return formattedContacts;
}

console.log(formatContact(contact)); 
</pre></code>
This example extracts keywords.edges.nodes from keywords and sets them into an array.
Reformats the Contact so that the keywords property is set as the previous array.

以上是关于markdown Ramda map和mapObjIndexed的主要内容,如果未能解决你的问题,请参考以下文章