javascriptramda.js

Transform an object with an array into an array


I have the following data structure:

const data = {
  "firstName": "A",
  "lastName": "B",
  "address": [{
    "country": "France",
    "city": "Paris"
  },
    {
      "country": "Italy",
      "city": "Rome"
    }
  ],
};

Using Ramda I would like to transforms it into:

const result = [
  {
    "firstName": "A",
    "lastName": "B",
    "address": {
      "country": "France",
      "city": "Paris"
    },
  },
  {
    "firstName": "A",
    "lastName": "B",
    "address": {
      "country": "Italy",
      "city": "Rome"
    },
  },
];

Solution

  • You can use a converge function to fork the prop address and then join it with the main object for each address in the list:

    /**
     * R.pick could be replaced with R.omit
     * to let you black list properties:
     * R.omit(['address']); https://ramdajs.com/docs/#omit
    **/
    const createByAddress = R.converge(R.map, [
      R.pipe(R.pick(['firstName', 'lastName']), R.flip(R.assoc('address'))),
      R.prop('address'),
    ]);
    
    const data = {
      "firstName": "A",
      "lastName": "B",
      "address": [{
        "country": "France",
        "city": "Paris"
        },
        {
          "country": "Italy",
          "city": "Rome"
        }
      ],
    };
    
    console.log(createByAddress(data));
    <script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.26.1/ramda.js" integrity="sha256-xB25ljGZ7K2VXnq087unEnoVhvTosWWtqXB4tAtZmHU=" crossorigin="anonymous"></script>