• 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
  • 相关阅读:
    redux的使用流程
    react类型检查
    将逻辑运算字符串转化为逻辑运算进行运算
    SQL 行列互换 天高地厚
    【转载】linux的IO调度算法和回写机制 天高地厚
    查询昨天的数据 天高地厚
    摘:DBA案例CPU占用100%的问题 天高地厚
    ASP.net HTTP/HTTPS自动切换 天高地厚
    网络连接和初始HTTP请求 天高地厚
    C++内存对象大会战 . 天高地厚
  • 原文地址:https://www.cnblogs.com/wang715100018066/p/16624910.html
Copyright © 2020-2023  润新知