更改对象的嵌套属性

时间:2016-07-08 15:34:37

标签: javascript ramda.js

型号:

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
        }
    }
}

Ramda代码:

 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值。我不明白。

3 个答案:

答案 0 :(得分:2)

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

如果您想保持对象完好无损,请更新'验证'财产,这可能会:

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

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

答案 1 :(得分:1)

所以,让我们通过你的替换者lambda。

x => x.validation = "replacement test"

您将x.validation = "replacement test"映射到x。如果你这样做

x => 1

然后该数组中的每个值都变为1。

使用map时,它会更改原始数组。在这种情况下,x变为x.validation,成为"replacement test"

在这种情况下使用forEach

R.foreach(x => x.validation = "replacement test");

答案 2 :(得分:0)

您正在对每次迭代应用某些内容,因此您分配给wordpress.com的事实无关紧要。

重要的是每次返回的内容以及发生的事情。基本上你只是返回字符串并每次都分配它,因此结果。