美文网首页
Object.keys,Object.values(),Obje

Object.keys,Object.values(),Obje

作者: 小棋子js | 来源:发表于2020-03-17 10:26 被阅读0次

    **Object.keys()** (取对象名)方法会返回一个由一个给定对象的自身可枚举属性组成的数组,数组中属性名的排列顺序和使用[for...in]循环遍历该对象时返回的顺序一致 。
    如果你想获取一个对象的所有属性,,甚至包括不可枚举的,请查看[Object.getOwnPropertyNames]

    在实际开发中,我们有时需要知道对象的所有属性;
    ES5 引入了Object.keys方法,成员是参数对象自身的(不含继承的)所有可遍历( enumerable )属性的键名。

    • 传入对象,返回属性名
    var data={a:1,b:2,c:9,d:4,e:5};
        console.log(Object.keys(data));//["a", "b", "c", "d", "e"]
        Object.keys(data).map((key,item)=>{
            console.log(key,data[key]);//key=>属性名    data[key]=>属性值
    });
    
    • 传入字符串,返回索引
    var str = 'ab1234';
    console.log(Object.keys(obj));  //[0,1,2,3,4,5]
    
    • 传入数组 返回索引
    var arr = ["a", "b", "c"];
        console.log(Object.keys(arr)); // console: ["0", "1", "2"]
    
    • 构造函数 返回空数组或者属性名
    function Pasta(name, age, gender) {
          this.name = name;
          this.age = age;
          this.gender = gender;
          this.toString = function () {
                return (this.name + ", " + this.age + ", " + this.gender);
        }
    }
    
    console.log(Object.keys(Pasta)); //console: []
    
    var spaghetti = new Pasta("Tom", 20, "male");
    console.log(Object.keys(spaghetti)); //console: ["name", "age", "gender", "toString"]
    

    扩展

    1. Object.values()取对象值
      Object.values方法返回一个数组,成员是参数对象自身的(不含继承的)所有可遍历( enumerable )属性的键值。Object.values()和Object.keys()是相反的操作,把一个对象的值转换为数组
    var data={a:1,b:2,c:9,d:4,e:5};
        console.log(Object.values(data));//[1, 2, 9, 4, 5]
        Object.values(data).map((key,item)=>{
            console.log(key,data[key]);//key=>属性值    data[key]=>undefined
    });
    
    1. Object.entries()把对象转换为一个键值对列表
      Object.entries方法返回一个数组,成员是参数对象自身的(不含继承的)所有可遍历( enumerable )属性的键值对数组
    var data={a:1,b:2,c:9,d:4,e:5};
        console.log(Object.entries(data));//[["a", 1], ["b", 2],["c", 9],["d", 4], ["e", 5]]
        Object.entries(data).map((key,item)=>{
            console.log(key);// key=>["a", 1],["b", 2],["c", 9],["d", 4],["e", 5]   
    });
    // 转换
    console.log(Object.entries({ name: 'JAY', age: 41 })); 
    //[ [ 'name', 'JAY' ], [ 'age', 41 ] ]
    
    console.log(Object.entries([1,2,3,4])) 
    //[ [ '0', 1 ], [ '1', 2 ], [ '2', 3 ], [ '3', 4 ] ]
    
    console.log(Object.entries('banana'))  
    //[ [ '0', 'b' ],[ '1', 'a' ],[ '2', 'n' ],[ '3', 'a' ],[ '4', 'n' ],[ '5', 'a' ] ]
    
    console.log(Object.entries(1)) //传入数字和浮点数返回 []
    
    // 将OBject 转换为map
    const obj = { name: 'JAY', age: 41 };
    const map = new Map(Object.entries(obj))
    console.log(map) 
    // Map { 'name' => 'JAY', 'age' => 41 }
    
    1. Object.fromEntries() 方法把键值对列表转换为一个对象。
      Object.fromEntries 列子
    // 转化map
    const map = new Map([
      ['name','周杰伦'],['age',36],
    ])
    
    console.log(Object.fromEntries(map)) 
    // {name: "周杰伦", age: 36}
    
    // 转化array
    const arr = [
      ['0', 'a'],
      ['1', 'b'],
      ['2', 'c']
    ];
    console.log(Object.fromEntries(arr)) 
    // {0: "a", 1: "b", 2: "c"}
    
    // 将对象中的属性数值统一*n
    const obj1 = {a:1,b:2,c:3,d:'isD'}
    const obj2 = Object.fromEntries(
      Object.entries(obj1).map(([key,val])=>{
        if(typeof val === 'number')return [key,val*2]
        else return [key,val]
      })
    )
    console.log(obj2) 
    //{a: 2, b: 4, c: 6, d: "isD"}
    
    // format url 
    
    const str = "age=zhoujielun&&name=16"
    const ar = new URLSearchParams(str)
    console.log(Object.fromEntries(ar)) 
    //{age: "zhoujielun", name: "16"}
    

    简易实现

    Object.entries
    const entries = (inArg)=>{
      if(Array.isArray(inArg)){
        return inArg.map((x,index)=>[`${index}`,x])
      }
      if(Object.prototype.toString.call(inArg) === `[object Object]`){
       return Object.keys(inArg).map(y=>[y,inArg[y]])
      }
      if(typeof inArg === 'number')return []
      throw 'Cannot convert argument to object'
    } 
    
    // test
    console.log(entries(1)) 
    // []
    
    console.log(entries([1,2,3])) 
    // [ [ '0', 1 ], [ '1', 2 ], [ '2', 3 ] ]
    
    console.log(entries({age:12,name:'ysss'})) 
    // [ [ 'age', 12 ], [ 'name', 'ysss' ] ]
    
    if(!Object.entries)Object.entries = entries;
    
    Object.fromEntries
    
    const fromEntries = (arrArg)=>{
      // Map
      if (Object.prototype.toString.call(arrArg) === '[object Map]') {
        const resMap = {};
        for (const key of arrArg.keys()) {
          resMap[key] = arrArg.get(key);
        }
        return resMap;
      }
      // array
      if(Array.isArray(arrArg)){
        const resArr = {}
        arrArg.map(([key,value])=>{
          resArr[key] =  value
        })
        return resArr
      }
      throw 'Uncaught TypeError: argument is not iterable';
    }
    
    // test 
    const map = new Map([
      ['name', '周杰伦'],
      ['age', 36]
    ]);
    console.log(fromEntries(map));
     // {name: "周杰伦", age: 36}
    
    const arr = [
      ['0', 'a'],
      ['1', 'b'],
      ['2', 'c']
    ];
    console.log(fromEntries(arr)) 
    // {0: "a", 1: "b", 2: "c"}
    
    // polyfill
    if(!Object.fromEntries)Object.fromEntries = fromEntries 
    
    

    相关文章

      网友评论

          本文标题:Object.keys,Object.values(),Obje

          本文链接:https://www.haomeiwen.com/subject/cjmzehtx.html