1 introduction

Daily business written too much have paralysis of the nerve, many should have known that knowledge has long been forgotten, we all know that function is first class citizens in JS, but unexpectedly someone {| zuo zhe} don’t even know the characteristics of it, is really ashamed.

2 the cause

In daily business development, it is common to give a default value in the data, and then replace the default value after requesting back-end data. If completely replacing the entire object is not what we want, some errors may occur, or some data may need to be modified. In this case, we need to write a function to replace each key corresponding to the value, just yesterday I encountered the same thing, without further discussion, directly to the code.

Form1 is the raw data
Form2 returns data for the back end
const mapForm = (form1, form2) = > {
  for (let key in form1) {
    if (key in form2) {
      form1[key] = form2[key]
    }
  }
}

const form1 = {
  name: ' '.age: 0
}
const form2 = {
  name: 'mazi'.age: 26
}
mapForm(form1, form2)
console.log(form1) // { name: 'mazi', age: 26 }
Copy the code

3 questions

Form1 has the same value as form2 after the mapForm function is called. This is exactly what I wanted to see, but I was confused at the time, because I didn’t know that there was a weak reference between the formal parameters and the actual parameters of the js function if it passed complex types. So this is going to change the data for form1.

4 to solve

Parse (json.stringify (obj)) if you have a similar situation in your code and you don’t want the form1 object to change, it is more convenient to use json.parse (json.stringify (obj) directly.

.- mapForm(form1, form2)
+ mapForm(JSON.parse(JSON.stringify(form1), form2)
console.log(form1) // { name: '', age: 0 }
Copy the code

Parse (json.stringify (obj)) is not a safe way to use json.parse (json.stringify (obj) directly, and some data types do not work as desired, so you can try using the cloneDeep function provided by the LoDash library as follows:

const objects = [{ 'a': 1 }, { 'b': 2 }]

const deep = _.cloneDeep(objects)
console.log(deep[0] === objects[0]) // false
Copy the code

If you think this article is helpful to you, please click the following button, thank you, I will update the article in succession.