Javascript 使用 ES6 中的 map 函数更新对象的属性值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/49627157/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 04:25:36  来源:igfitidea点击:

Update the attribute value of an object using the map function in ES6

javascriptarraysecmascript-6es6-map

提问by Rito

I am trying to code this in ES6. Below is what I am trying to achieve. Let's say I have an array of objects called schools.

我正在尝试在 ES6 中对此进行编码。以下是我正在努力实现的目标。假设我有一个名为schools.

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

Now, I want to write a function called editSchoolNamewhich will take 3 parameters, schools(which is the array I have defined above), oldNameand name.

现在,我想编写一个名为的函数editSchoolName,它将接受 3 个参数schools(这是我在上面定义的数组)oldNamename.

I will pass the name of the school in the parameter oldNameand that name should be updated with the value in the parameter name.

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

I don't want to change the state of the variable schoolsso I am using a mapfunction which will return a new array with the changes.

我不想更改变量的状态,schools因此我使用了一个map函数,该函数将返回一个包含更改的新数组。

The editSchoolNamefunction will be called like this -

editSchoolName函数将像这样被调用 -

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

Here, the name YorkTownshould be replaced with the name New Gen. So the expected value of the array updatedSchoolsshould be -

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

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

This is how my editSchoolName function looks like -

这就是我的 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;
        }
    });

Need help in making the change in the editSchoolNamefunction to achieve the above mentioned desired result.

需要帮助更改editSchoolName功能以实现上述预期结果。

采纳答案by Rahul Sharma

try this, ES6 Object.assign()to create copy of array element and update new object.

试试这个,ES6Object.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);

回答by klugjo

You need to return the updated object:

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

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

回答by Jonas Wilms

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

You could shorten it by using a ternary.

您可以通过使用三元来缩短它。

回答by Anurag Lal

If you want to edit only the commented part:

如果您只想编辑注释部分:

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

回答by Sumer

I wonder how come none of the answers give simple solution

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

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

回答by Dipak chavda

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");