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 }