简体   繁体   中英

array.map is mutating my original array

I am trying to update a field in an object in my array.

My object (simplified) looks something like this:

{
  "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"
    }
  ]
}

and I call it like this:

prepareRepositories(this.props.primarySearchRepositories);

I can have several similar repos and I loop through them. And for each item in the array readableStructure I am trying to add a property called QSString using the following code.

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

However, when I do this the original object is modified and the QSString property get set to the same thing for every repo.

What am I doing wrong?

Array.map does not change the original array, ie creates a new Array. However, any object in the Array continues to hold the same reference , hence, any change in object even inside map function will update the object in original array.

You need to create a copy for the object .

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

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

JSON.parse(JSON.stringify(your_object))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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