# entries 和 fromEntries 用法实践
# 1、获取指定属性
const obj = {
test1: 1,
test2: 2,
test3: 3,
test4: 4,
};
// 获取指定属性的对象
function getKeys1(obj, ...keys) {
const temp = Object.entries(obj).filter(([key]) => keys.includes(key));
return Object.fromEntries(temp);
}
console.log(getKeys1(obj, "test4", "test2", "test6"));
// { test2: 2, test4: 4 }
// 获取指定属性顺序的对象
function getKeys2(obj, ...keys) {
const temp = Object.entries(obj);
const tmp = [];
keys.forEach((i) => {
const finds = temp.find(([key]) => key === i);
finds && tmp.push(finds);
});
return Object.fromEntries(tmp);
}
console.log(getKeys2(obj, "test4", "test2", "test6"));
// { test4: 4, test2: 2 }
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
# 2、属性和值对调
// 属性和值对调
function getValueKey(obj) {
const temp = Object.entries(obj).map(([key, value]) => [value, key]);
return Object.fromEntries(temp);
}
console.log(getValueKey(obj));
// { '1': 'test1', '2': 'test2', '3': 'test3', '4': 'test4' }
1
2
3
4
5
6
7
8
2
3
4
5
6
7
8
# 3、自实现
// 实现entries方法
function myEntries(obj) {
const temp = [];
for (const key in obj) {
temp.push([key, obj[key]]);
}
return temp;
}
console.log(myEntries(obj));
// [ [ 'test1', 1 ], [ 'test2', 2 ], [ 'test3', 3 ], [ 'test4', 4 ] ]
// 实现fromEntries方法
function myFromEntries(list) {
const obj = {};
for (const [key, value] of list) {
let keyName;
if (typeof key === "string" || typeof key === "symbol") {
keyName = key;
} else {
keyName = String(key);
}
obj[keyName] = value;
}
return obj;
}
const list = [
["test1", 1],
["test2", 2],
["test3", 3],
["test4", 4],
];
console.log(myFromEntries(list));
// { test1: 1, test2: 2, test3: 3, test4: 4 }
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# 4、总结
获取指定属性:通过配合 filter 和 includes 方法来实现
属性和值对调:通过配合 map 方法来实现
实现 entries 方法:通过 for...in 来遍历对象
实现 fromEntries 方法:通过 for...of 来遍历数组,再进行组装
← 4.1-js对象详解 5.1-js函数 →