如何使用原型在对象内映射数组对象



我在获取原型映射函数以处理对象中的数组对象时遇到了一些问题。我得到错误"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);

尽量避免使用global变量:

Mapping.prototype.protoMap = function() {
// DON'T do this
// plus, this really doesn't make sense
// because `map` refers to the new `Mapping` object that
// you created; what you probably want to do is use the `mappedData`
// property on your newly created `Mapping` object
// const protoMap = map.mappedData.map(function(map) {...})
// instead, use `this` to access the `mappedData` property
// that you passed to the constructor
const protoMap = this.mappedData.map(function(item) {...})
}
const map = new Mapping(mapped)

请参阅代码片段中的注释,了解如何修复您的示例。

function Mapping(data = []) {
this.mappedData = data
}
Mapping.prototype.protoMap = function() {
// access the `mappedData` that was passed
// to the `Mapping` constructor using `this`
const protoMap = this.mappedData.map(
function(item) {
// use `item` argument for the `mappedData.map`
// callback to access each item inside `mappedData`
// individually
const temp = {}
temp["a"] = item["a"]
return temp
}
)
return protoMap
}
const data = [
{'a': 1, 'b': 2, 'c': 3},
{'a': 4, 'b': 5, 'c': 6},
{'a': 7, 'b': 8, 'c': 9}
]
const mapped = data.map(
function(data) {
const newMap = {}
newMap['a']=data['a']
newMap['b']=data['b']
return newMap;
}
)
const mapping = new Mapping(mapped)
const result = mapping.protoMap()
console.log('result', result)

您可以使用类似的方法来转换array to map。我很久以前就创建了这个util。

更多用途:

https://gist.github.com/deepakshrma/4b6a0a31b4582d6418ec4f76b7439781

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;
let data = [
{ a: 1, b: 2, c: 3 },
{ a: 4, b: 5, c: 6 },
{ a: 7, b: 8, c: 9 },
];
var dataMap = new Mapper(data, "a"); 
console.log(dataMap.map); 
if(typeof window !== 'undefined') window.Mapper = Mapper;

最新更新