gpt4 book ai didi

javascript - 更改对象的嵌套属性

转载 作者:行者123 更新时间:2023-11-30 11:55:04 26 4
gpt4 key购买 nike

型号:

function model() {
return {
title: {
"content": undefined,
"validation": {
"type": "string",
"required": true,
"minLength": 1,
"maxLength": 3,
validationErrorMessage: "Your title must be a valid string between 1 and 35 characters"
}
},

email: {
content: undefined,
validation: {
type: "email",
required: true,
minLength: 1,
maxLength: 60,
validationErrorMessage: "Your email must be between 1 and 50 characters"
}
},


link: {
content: undefined,
validation: {
type: "url",
required: true,
minLength: 1,
maxLength: 500,
validationErrorMessage: "Your link name must be a valid email between 1 and 50 characters"
}
},

description: {
content: undefined
}
}
}

lambda 代码:

 let test = R.map( x => console.log(x.validation), model)
console.log(test)

记录正确的结果:

{ type: 'string',
required: true,
minLength: 1,
maxLength: 3,
validationErrorMessage: 'Your title must be a valid string between 1 and 35 characters' }
{ type: 'email',
required: true,
minLength: 1,
maxLength: 60,
validationErrorMessage: 'Your email must be between 1 and 50 characters' }
{ type: 'url',
required: true,
minLength: 1,
maxLength: 500,
validationErrorMessage: 'Your link name must be a valid email between 1 and 50 characters' }
undefined
{ title: undefined,
email: undefined,
link: undefined,
description: undefined }

那为什么会这样:

   let test = R.map( x => x.validation = "replacement test", model)
console.log(test)

日志:

{ title: 'replacement test',
email: 'replacement test',
link: 'replacement test',
description: 'replacement test' }

我本以为 x.validation 内容会被替换,而不是整个 x 值。我不明白。

最佳答案

map,就像所有 Ramda 函数一样,旨在以不可变的方式使用。它返回一个列表,其中包含您从函数返回的元素。但是你不会(有意地)从你的函数中返回任何东西,只是调整原始值。不过,Javascript 正在从您的赋值表达式中返回,这是 ES6 箭头函数的一个很好的特性。

如果你想保持你的对象完好无损,但更新'validation'属性,这可能会做:

R.map(R.assoc('validation', 'replacement text'), model());

assoc对您的对象进行浅表克隆,用给定的值覆盖指定的属性。

关于javascript - 更改对象的嵌套属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38270496/

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