JS 对象相关方法

1. 判断是否为对象

1
2
Object.prototype.toString.call({}) === '[object Object]'
Object.prototype.toString.call([]) === '[object Array]'

2. 判断对象是否全等

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
const isObjectValueEqual = (a, b) => {
const aProps = Object.getOwnPropertyNames(a)
const bProps = Object.getOwnPropertyNames(b)
if (aProps.length !== bProps.length) {
return false
}
for (let i = 0; i < aProps.length; i++) {
const propName = aProps[i]
const propA = a[propName]
const propB = b[propName]
if (!Object.prototype.hasOwnProperty.call(b, propName)) return false
if ((propA instanceof Object)) {
if (!isObjectValueEqual(propA, propB)) {
return false
}
} else if (propA !== propB) {
return false
}
}
return true
}

3. 获取对象全部属性

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
obj = {
weixinSecret: '',
Appid: '',
Desc: '',
channelId: 0
}
console.info(Object.keys(obj)) // ["weixinSecret", "Appid", "Desc", "channelId"]
console.info(Object.getOwnPropertyNames(obj)) // ["weixinSecret", "Appid", "Desc", "channelId"]

for(a in obj) {
console.info(a)
}
// weixinSecret
// Appid
// Desc
// channelId

for(a of obj) {
console.info(a)
}
// Uncaught TypeError: obj is not iterable

4. 合并对象属性

1
2
obj = Object.assign(obj, {Desc: 'aaa', ChannelName: ''})
// {weixinSecret: '', Appid: '', Desc: 'aaa', channelId: 0, ChannelName: ''}

5. 判断对象是否为空

JavaScript 中如何判断对象是否为空 - 掘金 (juejin.cn)

1
2
3
4
5
6
7
8
9
10
const obj = {}
// 错误:空对象和空数组的布尔值都为 true
!Boolean(obj) // false

// hack
JSON.stringify(obj)==='{}' // true
JSON.stringify({name: function() {a: 'eee'}}) // '{}'

// 推荐
obj && Object.keys(obj).length === 0 && obj.constructor === Object // true

6. 判断对象是否存在某属性

1
2
var obj = { name: '小明' }
obj.hasOwnProperty('name') // true