vuejs copying data object and removing property will remove the property from original object as well

后端 未结 5 513
你的背包
你的背包 2021-02-01 09:27

I have a data object in vue that looks like this

rows[
0 {
  title: \"my title\",
  post: \"my post text\",
  public: false,
  info: \"some info\"
},
1 {
 title:         


        
5条回答
  •  孤城傲影
    2021-02-01 09:53

    it is because row is reference type and postData is pointing to same reference as row. To copy without reference (deep copy) you can use Object.assign if your object/array contains only value type ( like number, string , boolean etc) not reference type like Object or Array. If your Object contains reference type like object containing object then internal copied object will be reference type.

    Example 1:

    var user = {
    name: "abc",
    address: "cde"
    };
    
    var copiedUser = Object.assign({}, user); 
    

    it copies properties from user. So user and copiedUser are different object because user contains only value types

    Example 2:

    var user = {
    name: "abc",
    address: "cde",
    other_info: { // reference type
       country: "india"
    }
    
    };
    
    var copiedUser = Object.assign({}, user); 
    

    Now it copies all properties from user but user contains other_info that is reference type(object). so changing copiedUser properties which are value type will not affect user but changing other_info of copiedUser or user will affect each other.

    copiedUser.name ="new name"; // will not reflect in user

    copiedUser .other_info.country = "new country"; // will reflect in user also

    So Object.assign will copy to one level. If your object contains nested object or array you need to iterate and copy till last level.

    Object.assign takes {} as well as [] also. so you can return array also.

    eg:var copiedArray= Object.assign([], [1,3,4,5]);

    So for your case I think you need to iterate your array till object then copy and push them in another array;

    var rows = [
     {
      title: "my title",
      post: "my post text",
      public: false,
      info: "some info"
    },
    {
     title: "my title",
      post: "my post text",
      public: true,
      info: "some info"
    },
     {
     title: "my title",
      post: "my post text",
      public: false,
      info: "some info"
    }
    ];
    
    var postData = [];
    
    for(var i=0;i

提交回复
热议问题