Object.entries()
概述
Object.entries()方法返回一个给定对象自身可枚举属性的键值对数组,其排列与使用 for...in 循环遍历该对象时返回的顺序一致(区别在于 for-in 循环还会枚举原型链中的属性)
简单数组
const obj = { foo: 'bar', baz: 42 };
console.log(Object.entries(obj)); // [ ['foo', 'bar'], ['baz', 42] ]
类数组
const obj = { 0: 'a', 1: 'b', 2: 'c' };
console.log(Object.entries(obj)); // [ ['0', 'a'], ['1', 'b'], ['2', 'c'] ]
具有随机key排序的类数组对象
const anObj = { 100: 'a', 2: 'b', 7: 'c' };
console.log(Object.entries(anObj)); // [ ['2', 'b'], ['7', 'c'], ['100', 'a'] ]
getFoo是一个不可枚举的属性
const myObj = Object.create({}, { getFoo: { value() { return this.foo; } } });
myObj.foo = 'bar';
console.log(Object.entries(myObj)); // [ ['foo', 'bar'] ]
非对象参数将强制为对象
console.log(Object.entries('foo')); // [ ['0', 'f'], ['1', 'o'], ['2', 'o'] ]
遍历数组(配合for..of)
const object1 = {
a: 'somestring',
b: 42
};
for(const [key, value] of Object.entries(object1)){
console.log(`${key}:${value}`)
}
// expected output:
// "a: somestring"
// "b: 42"
通过entries变成数组使用附加项
Object.entries(obj).forEach(([key, value]) => {
console.log(`${key} ${value}`); // "a 5", "b 7", "c 9"
});
数组排序
const hash: { [K: string]: RecordItem[] } = {};
const selectedRecords = records.filter(r => r.category === category);
selectedRecords.map(r => {
const key = day(r.createdAt).format('YYYY年MM月DD日');
if (!(key in hash)) {
hash[key] = [];
}
hash[key].push(r);
});
const array = Object.entries(hash).sort((a, b) => {
if (a[0] === b[0]) return 0;
if (a[0] > b[0]) return -1;
if (a[0] < b[0]) return 1;
return 0;
})