1. Object.entries() 返回一个数组,数组里面的每一个元素是对象的可枚举属性的键值对;不包括Symbol值的属性。
function objectToArray() {
const tempObj = {
'fisrt':'firstValue',
'second':'secondValue',
'third':'thirdValue'
}
let tempArray = Object.entries(tempObj);
console.log(JSON.stringify(tempArray))
}
如上面方法,调用方法后,会返回一个数组,数组里面的元素,也是一个数组(元素数组里面第一个元素是key,第二个元素是对应的value);
[["fisrt","firstValue"],["second","secondValue"],["third","thirdValue"]]
2. Object.fromEntries()可以将一个键值对列表转换为对象。
function arrayToObject() {
const tempArray = [['fisrtKey',3],['secondKey',5]];
let tempObj = Object.fromEntries(tempArray)
console.log(JSON.stringify(tempObj))
}
例如上面方法,传入一个二维数组,里面的元素是一个键值对。运行上面的方法,将会返回
{"fisrtKey":3,"secondKey":5};
2.2 将一个Map转化为普通对象
function mapToArray() {
let tempMap = new Map();
tempMap.set('key1','value1');
tempMap.set('key2','value2');
console.log(Object.fromEntries(tempMap))
}
结果:{key1: 'value1', key2: 'value2'}
补充:我们看下如果调用Object.entries(),传入字符串对象,会返回什么?
function stringValueToArray() {
const tempString = 'abcde';
let tempArray = Object.entries(tempString);
console.log(JSON.stringify(tempArray))
}
stringValueToArray();
结果:[["0","a"],["1","b"],["2","c"],["3","d"],["4","e"]]