Object.entries()详解

文档:https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Object/entries

描述:Object.entries()返回一个数组,其元素是与直接在object上找到的可枚举属性键值对相对应的数组。属性的顺序与通过手动循环对象的属性值所给出的顺序相同。其排列与使用   for.....in   循环遍历该对象时返回的顺序一致(区别在于for...in)循环还会枚举原型链中的属性.

一、Object.entries(对象)

const object1 = {
  a: 'somestring',
  b: 42
};
let a = []
let b = []
  console.log(Object.entries(object1)) //[['a','somestring'],['b',42]]
for (const [key, value] of Object.entries(object1)) {
   console.log(`${key}: ${value}`);
   a.push(key)
b.push(value) }
// "a: somestring" // "b: 42" console.log(a) //[a,b] 不过直接用 Object.keys(object1)岂不香 console.log(b) //['somestring',42] 不过直接用 Object.values(object1)岂不香

 

二、Object.entries(数组对象)修改数组对象中的key,有text改为label。

const customerList=[{text:'1'},{text:'2'}]
// 返回新的组件
let newList = []
console.log(Object.entries(customerList))//[['0',{text:'1'}],['1',{text;'2'}]]
for (let [index, value] of Object.entries(customerList)) {
  newList.push({ index: index, label: value.text })
}
console.log(newList)//[{index:'0',label:'1'},{index:'1',label:'2'}]

 

三、Object转换成Map

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

const obj2 = { name: 'wang', age: 32, sex: 'man' }; 
console.log(Object.entries(obj2));//[['name','wang'],['age',32],['sex','man']]
const map = new Map(Object.entries(obj2)); 
console.log(map); //Map(3) {'name' => 'wang', 'age' => 32, 'sex' => 'man'}
console.log(map.size); // 3
map.delete('name') 
console.log(map) //Map(2) {'age' => 32, 'sex' => 'man'}
console.log(map.get('age')) // 32

 

posted @ 2022-08-25 17:05  最爱小虾  阅读(1837)  评论(0编辑  收藏  举报