繁体   English   中英

array.map正在改变我的原始数组

[英]array.map is mutating my original array

我正在尝试更新数组中对象的字段。

我的对象(简化)看起来像这样:

{
  "readableStructure": [
    {
      "ID": "1",
      "Name": "Name 1",
      "Description": "Adding, updating or removing users",
      "IconName": "fas fa-users-cog"
    },
    {
      "ID": "2",
      "Name": "Name 2",
      "Description": "Views overview",
      "IconName": "fas fa-street-view"
    },
    {
      "ID": "3",
      "Name": "Name 3",
      "Description": "Improvements to apps",
      "IconName": "fas fa-broadcast-tower"
    },
    {
      "ID": "4",
      "Name": "Name 4",
      "Description": "Managing badges",
      "IconName": "fas fa-id-badge"
    },
    {
      "ID": "5",
      "Name": "Name 5",
      "Description": "Art",
      "IconName": "fas fa-hand-holding-heart"
    }
  ]
}

我这样称呼它:

prepareRepositories(this.props.primarySearchRepositories);

我可以有几个类似的存储库,并遍历它们。 而对于在阵列中的每个项目readableStructure我想添加一个名为属性QSString使用下面的代码。

prepareRepositories(repositories) {

    const repos = repositories.map((repo, index) => {

        const searchableColumns = ['Name', 'Description'];
        const newRepo = [];
        newRepo[0] = {};
        newRepo[0].readableStructure = [];

        newRepo[0].readableStructure = repo[0].readableStructure.map((item) => {
            item.QSString = this.getSearchableString(item, searchableColumns) || 'blaha';
            return item;
        });

        return newRepo;
    });

    return repos;
}

getSearchableString = (base, searchableColumns) => {
    let searchables = [];

    Object.keys(base).forEach((key) => {
        if ((searchableColumns.indexOf(key) > -1) && (base[key] !== null) && (typeof base[key] !== 'object')) {
            searchables.push(base[key]);
        }
    });

    const searchableString = searchables.join(' ');
    return searchableString;
}

但是,当我这样做时,原始对象将被修改,并且每个QSString属性都设置为相同的东西。

我究竟做错了什么?

Array.map不会更改原始数组,即创建一个新的Array。 但是,数组中的任何对象继续保持相同的引用 ,因此,即使在map函数内部,对象中的任何更改都将更新原始数组中的对象。

您需要为该对象创建一个副本

item = JSON.parse(JSON.stringify(item))

使用这个不会改变原始对象

JSON.parse(JSON.stringify(your_object))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM