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 }    
  • 相关阅读:
    BWList of logged on users in the Portal
    BASIS About Profile
    B/S C/S 打印
    程序员得学习观各种好书推荐
    ORACLE面试测试题目
    oracle经典20题(参考答案)
    程序员得学习观各种好书推荐
    Oracle笔试题
    Oracle笔试题
    Oracle里面常用的数据字典有哪些?
  • 原文地址:https://www.cnblogs.com/lilililiwang/p/15469897.html
Copyright © 2011-2022 走看看