js对象 转 数组对象

2024-05-10  本文已影响0人  小李不小

区别

Object.entries() 方法返回一个给定对象自身可枚举属性的键值对数组。

其排列与使用 for...in 循环遍历该对象时返回的顺序一致(区别在于 for-in 循环还会枚举原型链中的属性)。

用法

1,如果您想要将对象转换为数组对象,可以使用Object.entries()方法来获取对象的键值对,并将其转换为数组对象。例如:

let obj = {a: 1, b: 2, c: 3};

let arr = Object.entries(obj);

console.log(arr); // [["a", 1], ["b", 2], ["c", 3]]

2,参数为数组

const obj = [1,2,3,4,5,6]
const res = Object.entries(obj) 
console.log(res); 

结果


image.png

3,参数为数组(数组中包含对象 )

const obj = [1,2,3,4,5,6,{a:'a'},{b:'b'},{c:'c'}]
const res = Object.entries(obj) 
console.log(res); 

结果


image.png

4,参数为数组(数组中元素为对象)

const obj = [{a:'a'},{b:'b'},{c:'c'}]
const res = Object.entries(obj) 
console.log(res); 

image.png

5,Object转换为Map

new Map()构造函数接受一个可迭代的entries。借助Object.entries方法你可以很容易的将Object转换为Map。

const obj = { name: 'xiaoming', age: 'seven',sex: 'man', grade: 'four' }; 
console.log(Object.entries(obj));
const map = new Map(Object.entries(obj)); 
console.log(map); 

image.png

总结
Object.entries() 可以把一个对象的键值以数组的形式遍历出来,结果和 for...in 循环遍历该对象时返回的结果一样,但是不会遍历其原型属性。

上一篇 下一篇

猜你喜欢

热点阅读