1.使用展示语法完成对象合并 属性相同后面覆盖前面的属性 :
1.1浅克隆对象
//使用展示语法完成对象合并 属性相同后面覆盖前面的属性
let obj={
name:'yang',
height:200
}
let nameObj={
name:'zhang'
}
let newObj={...obj,...nameObj};
console.log(newObj)/* {name: "zhang", height: 200} */
//Object.entries()返回一个数组,其元素是与直接在object上找到的可枚举属性键值对相对应的数组。属性的顺序与通过手动循环对象的属性值所给出的顺序相同。
let obj={
name:'yang',
height:200
}
let obj1={
name:'1',
height:200
}
let a=Object.assign({},obj,obj1)
console.log(a);/* {name: "1", height: 200} */
1.2深度克隆对象
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
</body>
</html>
<script>
let obj1 = {
name: 'zhangsan',
list: [{
book: 'math',
grade: 90
}, {
book: 'English',
grade: 100
}],
info: {
friend: 'kb',
height: 100
},
age: 20
}
//深度克隆对象的方法:
function copy(obj) {
//使用 instanceof 就是判断一个实例是否属于某种类型
let result = obj instanceof Array ? [] : {};
for (const [k, v] of Object.entries(obj)) {
result[k] = typeof v == 'object' ? copy(v) : v
}
return result
}
let obj2 = copy(obj1);
obj2.list.push({
book: 'yige',
grade: 100
})
console.log(JSON.stringify(obj2, null, 2));
console.log(JSON.stringify(obj1, null, 2));
/*
obj2:====
{
"name": "zhangsan",
"list": [
{
"book": "math",
"grade": 90
},
{
"book": "English",
"grade": 100
},
{
"book": "yige",
"grade": 100
}
],
"info": {
"friend": "kb",
"height": 100
},
"age": 20
}
obj1:======
{
"name": "zhangsan",
"list": [
{
"book": "math",
"grade": 90
},
{
"book": "English",
"grade": 100
}
],
"info": {
"friend": "kb",
"height": 100
},
"age": 20
}
*/
</script>
2.判断对象自身属性是否含有某个属性
let obj={
name:'yang',
height:200
}
console.log(obj.hasOwnProperty('name'))//true 判断对象自身属性是否含有某个属性
console.log("name1" in obj)//false 判断自身和原型上是否有某个属性返回布尔值
3.对象Object.keys()/Object.values()/Object.entries方法
//Object.entries()返回一个数组,其元素是与直接在object上找到的可枚举属性键值对相对应的数组。属性的顺序与通过手动循环对象的属性值所给出的顺序相同。
let obj={
name:'yang',
height:200
}
console.log(JSON.stringify(Object.entries(obj)));/* [["name","yang"],["height",200]] */
//
let obj={
name:'yang',
height:200
}
console.log(Object.keys(obj));//["name", "height"]属性名组成的数组
console.log(Object.values(obj));//["yang", 200]属性值组成的数组
//将对象变成可迭代的数组 之后就可以使用for of
for (const [key,val] of Object.entries(obj)) {
console.log(key,val)/* name yang
dd.html:58 height 200 */
}
4.数组对象转换为对象的形式
//数组对象转换为对象的形式
let arr=[
{name:'yang',age:23,goods:'apple'},
{name:'yang1',age:23,goods:'apple'},
{name:'yang2',age:23,goods:'apple'},
]
let goo=arr.reduce((pre,cur,index)=>{
pre[`${cur.name}-${index+1}`]=cur;
return pre
},{})
console.log(JSON.stringify(goo,null,2));/*
{
"yang-1": {
"name": "yang",
"age": 23,
"goods": "apple"
},
"yang1-2": {
"name": "yang1",
"age": 23,
"goods": "apple"
},
"yang2-3": {
"name": "yang2",
"age": 23,
"goods": "apple"
}
}
*/