gpt4 book ai didi

javascript - 更新对象值 Ramda

转载 作者:行者123 更新时间:2023-11-30 09:11:21 25 4
gpt4 key购买 nike

在上一个问题中,我尝试按父 ID 对数组进行分组,然后将它们从每个对象中删除 - Group arrays by parent ids object Ramda .

但是现在我有一个新问题。例如,我想更新 id 为 12 的对象中的标题。

我的数据模型:

const stuff = {
"31": [
{
"id": "11",
"title": "ramda heeeelp"
},
{
"id": "12",
"title": "ramda 123"
}
],
"33": [
{
"id": "3",
"title": "..."
}
],
"4321": [
{
"id": "1",
"title": "hello world"
}
]
}

尝试:

const alter = (id, key, value) => pipe(
values,
flatten,
update(...) // <= end of my attempts
// then group again
)

alter('12', 'title', 'new heading 123')(stuff)

最佳答案

您可以使用 lenses这里:

  1. 结束:https://ramdajs.com/docs/#over
  2. 集合:https://ramdajs.com/docs/#set

const titleLens = R.curry((key, id, data) => R.lensPath([
key,
R.findIndex(R.whereEq({ id }), R.propOr([], key, data)),
'title'
]));

// ----
const stuff = {
"31": [
{
"id": "11",
"title": "ramda heeeelp"
},
{
"id": "12",
"title": "ramda 123"
}
],
"33": [
{
"id": "3",
"title": "..."
}
],
"4321": [
{
"id": "1",
"title": "hello world"
}
]
}

const title3111 = titleLens('31', '11', stuff);
const result = R.set(title3111, 'DID RAMDA HELP YOU?', stuff);

console.log('result', result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.26.1/ramda.js" integrity="sha256-xB25ljGZ7K2VXnq087unEnoVhvTosWWtqXB4tAtZmHU=" crossorigin="anonymous"></script>

关于javascript - 更新对象值 Ramda,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58693528/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com