我在使原型映射函数与对象内部的数组对象一起使用时遇到一些问题。我收到错误“ x()不是函数”。我知道您不能在对象上使用原型,但是应该使用obj.arr.map()可以访问对象内的数组。
这是我的代码:
let data = [
{'a':1, 'b':2, 'c':3},
{'a':4, 'b':5, 'c':6},
{'a':7, 'b':8, 'c':9}
]
let mapped = data.map(function(data){
let newMap = {}
newMap['a']=data['a']
newMap['b']=data['b']
return newMap;
});
Mapping.prototype.protoMap = function(){
//I have tried writing it as map.data
let protoMap = map.map(function(map){
let protoMap1 = {}
protoMap1['a'] = map.mappedData['a']
return protoMap1;
});
}
function Mapping(data = []){
this.mappedData = data
};
let map = new Mapping(mapped);
您可以使用类似的方法转换array to map
。我很早以前就创建了这个实用程序。
class Mapper {
constructor(array, key) {
this.map = array.reduce((map, item) => {
const val = item[key];
if (!map[val]) {
map[val] = [];
}
map[val].push(item);
return map;
}, {});
}
find(key) {
return this.map[key] && this.map[key][Mapper.FIRST_INDEX]; //return blank array
}
findAll(key, returnUndefined) {
//return blank array
return this.map[key] ? this.map[key] : returnUndefined ? undefined : [];
}
}
Mapper.FIRST_INDEX = 0;
const users = [
{
_id: "57e88c892727ab7f4828c015",
isActive: true,
balance: "$1,807.06",
picture: "http://placehold.it/32x32",
age: 21,
name: "Schmidt"
},
{
_id: "57e88c897a849644b79d6555",
isActive: false,
balance: "$1,487.94",
picture: "http://placehold.it/32x32",
age: 40,
name: "Griffin"
},
{
_id: "57e88c89075380040077b307",
isActive: false,
balance: "$2,939.40",
picture: "http://placehold.it/32x32",
age: 22,
name: "Nellie"
},
{
_id: "57e88c89cbfe5ec2c41ae27f",
isActive: true,
balance: "$2,392.49",
picture: "http://placehold.it/32x32",
age: 36,
name: "Nellie"
},
{
_id: "57e88c89ace3c83d92a0de7f",
isActive: true,
balance: "$2,161.58",
picture: "http://placehold.it/32x32",
age: 40,
name: "Payne"
},
{
_id: "57e88c895cec7aa54f7409cb",
isActive: false,
balance: "$2,109.69",
picture: "http://placehold.it/32x32",
age: 37,
name: "Sandoval"
}
];
//How to use
var userMapper = new Mapper(users, "name"); // create a map on names
console.log(userMapper.find("Schmidt")); //will return only user with name 'Schmidt'
const userToFind = ["Payne", "Schmidt"];
const reqUsers = userToFind.map(name => userMapper.find(name));
console.log(reqUsers);
var userMapper = new Mapper(users, "isActive"); // create a map on isActive
console.log(userMapper.find(true)); //will return only first active user
console.log(userMapper.findAll(true)); //will return all active user
var userMapper = new Mapper(users, "name"); // create a map on names
console.log(userMapper.find("Nellie")); //will return only first user with name 'Nellie'
console.log(userMapper.findAll("Nellie").map(({ _id }) => _id));
//will return all user _id whose name is 'Nellie'
console.log(userMapper.map); //will return map based on name