T
T
toly192017-12-28 17:09:39
JavaScript
toly19, 2017-12-28 17:09:39

How to change the value for all array elements in Ramda.js?

There is an array

let arr = [{
  enabled: true,
  categories: [{
    enabled: false
    //...
  }, {
    enabled: false
  }, {
    enabled: true
  }]
}]

I need to set the enabled property to true on all elements of the categories property

Answer the question

In order to leave comments, you need to log in

3 answer(s)
M
Mikhail Osher, 2017-12-28
@miraage

Not sure if this is the most concise solution..

const R = require('ramda');

const input = [{
  enabled: true,
  categories: [{
    enabled: false,
  }, {
    enabled: false,
  }, {
    enabled: true,
  }],
}];

const setEnabled = entry => {
  if (entry.enabled) {
    return entry;
  }

  return Object.assign({}, entry, { enabled: true });
};

const walkCategory = entry => {
  return Object.assign({}, entry, {
    categories: R.map(setEnabled, entry.categories),
  });
};

const result = R.map(walkCategory, input);

console.log(JSON.stringify(result, null, 2));

[
  {
    "enabled": true,
    "categories": [
      {
        "enabled": true
      },
      {
        "enabled": true
      },
      {
        "enabled": true
      }
    ]
  }
]

E
Evgeny Kalibrov, 2017-12-28
@rework

only for all elements of the categories property

var input = [{
  enabled: true,
  categories: [{
    enabled: false,
  }, {
    enabled: false,
  }, {
    enabled: true,
  }],
}];

const walkCategory = entry => {
  return Object.assign({}, entry, { enabled: true });
};

input[0].categories = R.map(walkCategory, input[0].categories);

console.log(input);

D
devunion, 2018-03-05
@devunion

Sorry, I rarely use Ramda, but can't you just do this?
or like this, if you need to turn it off:

const enableCat = enabled => cat => cat.enabled = enabled;
R.map(enableCat(true), input[0].categories);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question