const createArrFromObj = (arr, keys) => {
let newArr = []
if(typeof(keys) == 'string') {
newArr = arr.map(item => item[keys])
}else if(Array.isArray(keys)) {
let len = keys.length
newArr = arr.map(item => {
let i = -1;
let item_ = {}
while(++i < len) {
// console.log(item, keys[i]);
item_[keys[i]] = item[keys[i]]
}
return item_
});
}
return newArr
}
// example
var arr = [{a: 1, b: 2, c: 3}, {a: 4, b: 5, c: 6}]
createArrFromObj(arr, ['a', 'b']) // [{a: 1, b: 2}, {a: 4, b: 5}]
网友评论