Object.assign()方法合并两个js对象
MDN文档对该方法的描述如下
即形如Object.assign(obj1, obj2)
的语法中,会将obj1
和obj2
的所有属性合并,并返回新的对象。
手写测试
<template>
<div id="app">
<img alt="Vue logo" src="./assets/logo.png">
<HelloWorld msg="Welcome to Your Vue.js App"/>
</div>
</template>
<script>
import HelloWorld from './components/HelloWorld.vue'
export default {
name: 'App',
components: {
HelloWorld
},
data() {
return {
obj1: {
key1: 1,
key2: 2,
methods: {
test() {
console.log('test');
}
}
}
}
},
created() {
const obj2 = {
key2: '4',
key3: 3,
methods: {
test2() {
console.log('test2');
},
test3() {
console.log('test3');
}
}
};
const newObj = Object.assign(this.obj1, obj2);
console.log(newObj);
newObj.methods.test2();
newObj.methods.test();
},
}
</script>
<style>
#app {
font-family: Avenir, Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
margin-top: 60px;
}
</style>
运行效果
注意
obj2.key2
会覆盖掉obj1.key2
的值,并且obj2.methods
也会覆盖obj1.methods
思考
多个obj合并会如何?
const obj2 = {
key2: '4',
key3: 3,
methods: {
test2() {
console.log('test2');
},
test3() {
console.log('test3');
}
}
};
const obj3 = {
key3: 99
};
const newObj = Object.assign(this.obj1, obj2, obj3);
console.log(newObj);
newObj.methods.test2();
newObj.methods.test();
方法传入多个对象参数时,始终以最后的key3为最终有效值
使用Object.assign方法动态合并的对象与vue实例的响应式关系
<template>
<div id="app">
<img alt="Vue logo" src="./assets/logo.png">
<span>{{ newObj.key3 }}</span>
<HelloWorld msg="Welcome to Your Vue.js App"/>
</div>
</template>
<script>
import HelloWorld from './components/HelloWorld.vue'
export default {
name: 'App',
components: {
HelloWorld
},
data() {
return {
obj1: {
key1: 1,
key2: 2,
methods: {
test() {
console.log('test');
}
}
},
newObj: null
}
},
created() {
const obj2 = {
key2: '4',
key3: 3,
methods: {
test2() {
console.log('test2');
},
test3() {
console.log('test3');
}
}
};
const obj3 = {
key3: 99
};
this.newObj = Object.assign(this.obj1, obj2, obj3);
},
}
</script>
<style>
#app {
font-family: Avenir, Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
margin-top: 60px;
}
</style>
可以看到,初始化时data中的响应式数据里并没有key3
键,但是使用assign方法后续加上的key3
属性仍然正常显示在页面,所以该属性动态添加后是响应式的,并没有深度响应的问题。