【问题标题】:Update the attribute value of an object using the map function in ES6使用 ES6 中的 map 函数更新对象的属性值
【发布时间】:2018-09-12 14:35:09
【问题描述】:

我正在尝试在 ES6 中编写代码。以下是我想要实现的目标。假设我有一个名为 schools 的对象数组。

let schools = [
    {name: 'YorkTown', country: 'Spain'},
    {name: 'Stanford', country: 'USA'},
    {name: 'Gymnasium Achern', country: 'Germany'}
];

现在,我想编写一个名为 editSchoolName 的函数,它将采用 3 个参数,schools(这是我在上面定义的数组)、oldName 和 name。

我将在参数oldName 中传递学校的名称,并且该名称应使用参数name 中的值进行更新。

我不想更改变量schools 的状态,所以我使用map 函数,它将返回一个包含更改的新数组。

editSchoolName 函数会这样调用 -

var updatedSchools = editSchoolName(schools, "YorkTown", "New Gen");

在这里,名称YorkTown 应替换为名称New Gen。所以数组updatedSchools的期望值应该是-

let updatedSchools = [
    {name: 'New Gen', country: 'Spain'},
    {name: 'Stanford', country: 'USA'},
    {name: 'Gymnasium Achern', country: 'Germany'}
];

这就是我的 editSchoolName 函数的样子 -

const editSchoolName = (schools, oldName, name) =>
    schools.map(item => {
        if (item.name === oldName) {
          /* This is the part where I need the logic */
        } else {
          return item;
        }
    });

在更改editSchoolName 函数以实现上述预期结果时需要帮助。

【问题讨论】:

    标签: javascript arrays ecmascript-6 es6-map


    【解决方案1】:

    试试这个,ES6 Object.assign() 创建数组元素的副本并更新新对象。

    let schools = [{
            name: 'YorkTown',
            country: 'Spain'
        },
        {
            name: 'Stanford',
            country: 'USA'
        },
        {
            name: 'Gymnasium Achern',
            country: 'Germany'
        }
    ];
    
    const editSchoolName = (schools, oldName, name) => {
        return schools.map(item => {
            var temp = Object.assign({}, item);
            if (temp.name === oldName) {
                temp.name = name;
            }
            return temp;
        });
    }
    
    var updatedSchools = editSchoolName(schools, "YorkTown", "New Gen");
    console.log(updatedSchools);
    console.log(schools);

    使用解构

    const schools = [
      {
        name: "YorkTown",
        country: "Spain",
      },
      {
        name: "Stanford",
        country: "USA",
      },
      {
        name: "Gymnasium Achern",
        country: "Germany",
      },
    ];
    const editSchoolName = (schools, oldName, newName) =>
      schools.map(({ name, ...school }) => ({
        ...school,
        name: oldName === name ? newName : name,
      }));
    const updatedSchools = editSchoolName(schools, "YorkTown", "New Gen");
    console.log(updatedSchools);

    【讨论】:

      【解决方案2】:

      就这么简单:

      const editSchoolName = ((schools, oldName, name) =>{
          let results =schools.map((item,index) => { 
              if (item.name === oldName) {
                  let newItem = {...item, name} 
                  return newItem;
          } else {
              return item;    
          }
          });
          return results;
      });
      

      【讨论】:

        【解决方案3】:

        我想知道为什么没有一个答案给出简单的解决方案

        const editSchoolName = (schools, oldName, newName) =>
              schools.map(school => { if (school.name === oldName) school.name = newName;
              return school; 
        });
        

        【讨论】:

        • 您的代码的问题在于,它改变了原始数组。因为它是对数组及其子属性的引用,例如使用 school.name = newName 您可以更改原始数组的 name 属性...
        【解决方案4】:

        如果您只想编辑评论部分:

        const editSchoolName = (schools, oldName, name) =>
            schools.map(item => {
                if (item.name === oldName) {
                  var newItem = Object.assign({},item);
                  newItem.name = name;
                  return newItem;
                }
                else{
                  return item;
                }
            });
        

        【讨论】:

        • 它正在更新schools数组的值,这是不需要的。
        【解决方案5】:

        let schools = [{
            name: 'YorkTown',
            country: 'Spain'
          },
          {
            name: 'Stanford',
            country: 'USA'
          },
          {
            name: 'Gymnasium Achern',
            country: 'Germany'
          }
        ];
        
        let updatedSchools = [{
            name: 'New Gen',
            country: 'Spain'
          },
          {
            name: 'Stanford',
            country: 'USA'
          },
          {
            name: 'Gymnasium Achern',
            country: 'Germany'
          }
        ];
        
        const editSchoolName = ((schools, oldName, name) =>{
          schools.map(item => {
            if (item.name === oldName) {
              item.name = name;
              return item.name;
            } else {
              return item;
            }
          });
          console.log(schools);
        });
        
        editSchoolName(schools, 'YorkTown', "New Gen");

        【讨论】:

          【解决方案6】:
             const editSchoolName = (schools, oldName, newName) =>
              schools.map(({name, ...school }) => ({ ...school, name: oldName === name ? newName : name }));
          

          你可以使用三元来缩短它。

          【讨论】:

          • 这是纯函数式的选择。因为在每次迭代中,都会为结果数组创建一个新对象。
          【解决方案7】:

          您需要返回更新后的对象:

          const editSchoolName = (schools, oldName, name) =>
            schools.map(item => {
                if (item.name === oldName) {
                  return {...item, name};
                } else {
                  return item;
                }
          });
          

          【讨论】:

          • 请注意,schools 保持不变。 map 返回一个新数组。
          • 值得注意的是,对象传播标点符号不是 ES2015(又名 ES6)的一部分。更多支持的解决方案是将其脱糖到Object.assign({}, item, { name })
          • @YuryTarabanko 但同样值得注意的是 ES2018 已于 1 月完成,因此现在使用应该非常安全。当然可以为旧版浏览器转译。
          • @Keith Question 标签明确指出ecmascript-6 :)
          • 嘿@klugjo,我试图实现它,但由于某种原因,它抛出了一个错误。你可以在这里找到代码:es6console.com/jfjjqehr 它说的是意外令牌。你能帮我弄清楚我做错了什么吗?
          猜你喜欢
          • 2021-12-21
          • 1970-01-01
          • 2023-04-03
          • 2019-10-28
          • 2019-05-02
          • 2018-11-13
          • 1970-01-01
          • 1970-01-01
          • 2016-09-13
          相关资源
          最近更新 更多