使用Ramda.js更改对象数组中的对象属性

问题描述 投票:0回答:2

我有一个这样的对象数组:

[
  {type: 'x', 'attributes': {status: 'emitted', num: 1}}, 
  {type: 'y', attributes: {status: 'changed', num: 2}}
]

我想将每个状态更改为:[已完成],并且将每个状态更改为[错误]。

我该如何使用ramda?

node.js ramda.js
2个回答
1
投票

创建状态及其替换的Map,以及在给定值(updateStatus)时返回替换的函数(current)。使用R.map迭代数组,然后使用R.evolve创建状态更新的新对象。

const status = new Map([['emitted', 'done'], ['changed', 'error']])

// get the current state replacement from the Map or use current if no replacement is available
const updateStatus = current => status.get(current) || current

const fn = R.map(R.evolve({
  attributes: {
    status: updateStatus
  }
}))

const data = [{type: 'x', 'attributes': {status: 'emitted', num: 1}}, { type: 'y', attributes: {status: 'changed', num: 2}}]

const result = fn(data)

console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.27.0/ramda.js"></script>

0
投票

为了充分理解ramda提供的API,我认为添加“纯文本” javascript替代项(如果您愿意使用ECMAScript 2018 Object Spread syntax)是值得的。

在函数自变量中,您可以对对象进行解构,直到要修改的属性为止。所有其他道具都收集在...rest参数中。

在map函数的主体中,您重新创建一个新对象,对所需的属性进行修改。

如您所见,解析出要更改的部分可能非常困难。对ramda方法+1🙂

const entries = [ { type: 'x', 'attributes': {status: 'emitted', num: 1}}, { type: 'y', attributes: {status: 'changed', num: 2 } } ];

const statusMap = { "emitted": "done", "changed": "error" };

console.log(
  entries.map(
    ({ attributes: { status, ...ra }, ...re }) =>
    ({ attributes: { status: statusMap[status], ...ra }, ...re })
  )
);
© www.soinside.com 2019 - 2024. All rights reserved.