这里我试图将Cars1记录与myArray记录进行比较,如果它们匹配,我想将所选属性设置为MyArray的true以匹配记录。
myArray的abc.mp3,lmn.mp3,ggg.mp3与cars1的abc.mp3,lmn.mp3匹配,因为Abc.mp3在两个数组中都匹配。
这里Abc.mp3,lmn.mp3,ggg.mp3是3个不同的记录,所以在用逗号分割之后如果任何字符串在cars1中匹配(用逗号分隔)那么 将flag设置为true。
预期输出:
var myArray = [
{field: 'Abc.mp3,lmn.mp3,ggg.mp3', flag: true}, //Abc.mp3 is matching
{field: 'kkk.mp3', flag: false},
{field: 'Xyz.mp3', flag: true}, //Xyz.mp3 is matching
{field: 'MMM.mp3,UUU.mp3', flag: true}, //UUU.mp3 is matching
];
var myArray = [
{field: 'Abc.mp3,lmn.mp3,ggg.mp3', flag: false},
{field: 'kkk.mp3', flag: false},
{field: 'Xyz.mp3', flag: false},
{field: 'MMM.mp3,UUU.mp3', flag: false},
];
var cars1 = ["Abc.mp3,lmn.mp3", "Xyz.mp3","UUU.mp3"];
var cars2 = ["S1","S2","S3" ];
var array2 =[];
var map = Object.create(null);
cars1.forEach(function (entry, index) {
map[entry] = index;
});
array2 = myArray.map(function (item) {
var index = map[item.field];
if (index === undefined) {
return undefined;
}
item.flag = true;
return cars2[index];
});
console.log(myArray);

更新 现在cars1和cars2记录彼此之间有1对1的关系,这意味着车辆的abc.mp3,lmn.mp3分别指向cars2的S1。
当匹配myarray与Cars1时,如果找到匹配,那么我想记下cars1的索引并根据该索引我想从cars2获取记录并在该索引位置分配给array2。
例如:myArray和abc.mp3的abc.mp3,lmn.mp3,ggg.mp3,cars1的lmn.mp3匹配,因此Abc.mp3,lmn.mp3的索引为0所以基于此索引得到0th来自cars2的索引记录并在第0个索引处分配给array2。对于Xyz.mp3,S2将位于array2中的第2个位置。
array2中的预期输出:
array2 = ["S1" ,undefined, "S2","S3" ];
答案 0 :(得分:1)
你在找这样的东西吗?
var myArray = [
{field: 'Abc.mp3,lmn.mp3,ggg.mp3', flag: false},
{field: 'kkk.mp3', flag: false},
{field: 'Xyz.mp3', flag: false},
{field: 'MMM.mp3,UUU.mp3', flag: false},
];
var cars1 = ["Abc.mp3,lmn.mp3", "Xyz.mp3","UUU.mp3"];
var carsHash = cars1.reduce(function(p,c) {
var split = c.split(",");
split.forEach(function(i) { p[i] = true; });
return p;
},{});
myArray.forEach(function(i) {
var split = i.field.split(",");
i.flag = split.some(function(v) { return carsHash[v]; });
});
console.log(myArray);
首先,我们创建一个哈希来自cars1
的所有子串。然后我们循环浏览myArray
,如果field
中存在carsHash
中的任何子字符串,我们会将i.flag
设置为true。
答案 1 :(得分:1)
所以你想要这样的东西我想:
function match(data, selectors) {
return selectors.map(function(selector) {
let matchedIndex = -1;
return Object.assign({}, selector, {
flag: data.some(function(item, index) {
return selector.field.split(',').some(function(s) {
if(item.split(',').indexOf(s) > -1) {
matchedIndex = index;
return true;
}
return false;
});
}),
matchedIndex: matchedIndex
});
});
}
var myArray = [
{field: 'Abc.mp3,lmn.mp3,ggg.mp3', flag: false},
{field: 'kkk.mp3', flag: false},
{field: 'Xyz.mp3', flag: false},
{field: 'MMM.mp3,UUU.mp3', flag: false},
];
var cars = ["Abc.mp3,lmn.mp3", "Xyz.mp3","UUU.mp3"];
var cars2 = ["S1", "S2", "S3"];
var matched = match(cars, myArray);
var matchedFields = matched.filter(function(item) { return item.flag });
console.log(matched);
console.log(matchedFields);
var matchedCars2 = matched.map(function(item) { return cars2[item.matchedIndex]});
console.log('matched cars 2', matchedCars2);