Home > Software engineering >  Convert object with arrays to array of objects using Ramda
Convert object with arrays to array of objects using Ramda

Time:06-01

Example input:

const obj = {
  paths: ['path1', 'path2'],
  thumbnails: ['thumb1', 'thumb2'],
  sizes: [ // may not always be presented
    [100, 200],
    [120, 220],
  ],
};

Expected output:

const result = [
  {
    path: 'path1',
    thumbnail: 'thumb1',
    size: [100, 200],
  },
  {
    path: 'path2',
    thumbnail: 'thumb2',
    size: [120, 220],
  },
];

Bonus points for:

const result1 = [
  {
    path: 'path1',
    thumbnail: 'thumb1',
    width: 100,
    height: 200,
  },
  {
    path: 'path2',
    thumbnail: 'thumb2',
    width: 120,
    height: 220,
  },
];

// without sizes

const result2 = [
  {
    path: 'path1',
    thumbnail: 'thumb1',
  },
  {
    path: 'path2',
    thumbnail: 'thumb2',
  },
];

How would I achieve this with Ramda?

CodePudding user response:

You specifically want to do this using ramada only ?

Coz this can be achieved with vanilla as follows.

for expected output -

obj.paths.map((e, i) => ({ path: obj.paths[i], thumbnail: obj.thumbnails[i], size: obj.sizes[i] }))

for bonus output -

obj.paths.map((e, i) => ({ path: obj.paths[i], thumbnail: obj.thumbnails[i], width: obj.sizes[i][0], height: obj.sizes[i][1] }))

size array can be empty ie. [] -

obj.paths.map((e, i) => ({ path: obj.paths[i], thumbnail: obj.thumbnails[i], width: obj.sizes[i] !== undefined ? obj.sizes[i][0] : '', height: obj.sizes[i] !== undefined ? obj.sizes[i][1] : ''}))

CodePudding user response:

With vanilla Javascript, we can handle with indices easily, but Ramda.js does not have them, so you can use R.forEachObjIndexed to handle your case.

const obj = {
  paths: ['path1', 'path2'],
  thumbnails: ['thumb1', 'thumb2'],
  sizes: [ // may not always be presented
    [100, 200],
    [120, 220],
  ],
};

const result = []
R.forEachObjIndexed((value, index) => {
  const currentData = {
    path: value,
  }
  if(obj.thumbnails && obj.thumbnails[index]) {
    currentData.thumbnail = obj.thumbnails[index]
  }
  if(obj.sizes && obj.sizes[index]) {
    const [width, height] = obj.sizes[index]
    currentData.width = width
    currentData.height = height
  }
  result.push(currentData)
}, obj.paths)

console.log(result)

You can try out with the playground here

  • Related