zoukankan      html  css  js  c++  java
  • js把一个包含多个属性的对象,拷贝部分属性到一个新的对象

    let arr = [{name: "lucy", age: 100, sex: "female"}, {name: "mary", age: 43, sex: "female"}, {name: "curry", age: 30, sex: "male"}, {name: "bob", age: 20, sex: "male"}]
    
    let targetArr = [{name: "lucy", age: 100}, {name: "mary", age: 43}, {name: "curry", age: 30}, {name: "bob", age: 20}]

    arr数组中的每个对象都有多个属性,提取一部分属性组成一个新的数组(以下方法省略了遍历)

    方法一:

    const obj = {
        a:1,
        b:2,
        c:3,
        d:4,
    };
    const {a,b,c} = obj;
    const obj1 = {a,b,c};
    console.log(obj1) //{a:1,b:2,c:3}

    方法二:(不需要的属性放前面,obj1就是剩下的)

    const obj = {
        a:1,
        b:2,
        c:3,
        d:4,
    };
    const {d,...obj1} = obj
    console.log(obj1) //{a:1,b:2,c:3}

    方法三:

    const obj2 = (({a, d, e}) => ({a, d, e}))(obj)

    最基础写法:

    let obj = {name: 'a', age: 19, sex: 'female'}
    let obj2 = {
      name: obj.name,
      age: obj.age    
    }

    未验证方法:

    const pick = (obj, arr) =>
    
        arr.reduce((iter, val) => (val in obj && (iter[val] = obj[val]), iter), {});
    
        
    
    let obj2 = pick(obj, ['a', 'd', 'e'])
    var obj = {
        a: 1,
        b: 2,
        c: 3,
        d: 4,
        e: 5
    };
    function extend(obj) {
        var o = {},
        attr = Array.prototype.slice.call(arguments).slice(1);
        attr.forEach(function(val, index) {
        if (val in obj) { o[val] = obj[val]; }
        });
        return o;
    }
    console.log(extend(obj, 'c', 'b')); //{ c: 3, b: 2 }    
  • 相关阅读:
    ubuntu下开发环境的搭建
    用移动存储设备安装Ubuntu全攻略
    LAMP服务器搭建
    PHP关闭提示、打印配置
    PHPmyadmin修改root密码
    转 sql2oracle
    SQL Server链接其他数据库服务器的方法(转)
    转(哈希查找)
    日语网址
    Reflector 右键注册
  • 原文地址:https://www.cnblogs.com/lilililiwang/p/15469897.html
Copyright © 2011-2022 走看看