我正在处理一些角度代码。目标是使用尽可能小的角度1.x功能,因为这将很快得到重构。
我正在比较一个数组
let subscription = [
"Cinemax Subscription",
"Disney Subscription",
"Encore Subscription",
"Epix Subscription",
"HBO Subscription",
"MLB Subscription",
"NBA Subscription",
"NHL Subscription",
"Division"
]
到具有键值关系的对象数组,该关系包含另一个数组。
let profiles = [
{
name:"1+ Adults in Household",
qualifiers: [
{
name: 'Number of adults in the household'
}
]
},
{
name: '75k',
qualifers: [
{
name: 'Division'
},
{
name: 'Income'
}
]
},
{
name: 'Time Warner',
qualifers: [
{
name: 'Division'
}
]
}
]
我在索引和循环中遇到了困难。
let = profilesFiltered = [];
最初我尝试使用过滤器和angular.for 每个来比较数组。
let filteredProfiles = subscription.filter( function (src) {
angular.forEach(profiles, function (key, index) {
if(src === key.qualifiers[index].name) {
profilesFiltered.push(key);
}
})
});
我在if语句中看到了
key.qualifiers[index].name // 'Number of adults in the household'
与
相比,启动正确subscription[0] // however, it will continue to 1 on the first object which isn't there.
我看到它是如何开始失败的。但我不确定如何正确循环** profiles **数组中的限定符。
所需的结果是那些 Division ,它是索引中的最后一个数组项。
profilesFiltered = [
{
name: '75k',
qualifers: [
{
name: 'Division'
},
{
name: 'Income'
}
]
},
{
name: 'Time Warner',
qualifers: [
{
name: 'Division'
}
]
}
]
此时非常感谢任何反馈。
由于
答案 0 :(得分:2)
只需使用filter()
和some()
:
profiles.filter(v => v.qualifiers.some(q => subscription.includes(q.name)));
let subscription = [
"Cinemax Subscription",
"Disney Subscription",
"Encore Subscription",
"Epix Subscription",
"HBO Subscription",
"MLB Subscription",
"NBA Subscription",
"NHL Subscription",
"Division"
]
let profiles = [{
name: "1+ Adults in Household",
qualifiers: [{
name: 'Number of adults in the household'
}]
},
{
name: '75k',
qualifiers: [{
name: 'Division'
},
{
name: 'Income'
}
]
},
{
name: 'Time Warner',
qualifiers: [{
name: 'Division'
}]
}
]
let res = profiles.filter(v => v.qualifiers.some(q => subscription.includes(q.name)));
console.log(res)
答案 1 :(得分:1)
您是否在寻找类似的内容,请查看我的代码
cleaned = arr.reject{ |e| e == :c }
cleaned.each { |e| handle(e) }
答案 2 :(得分:-1)
这是您的数据结构的工作代码。它基于使用reduce函数。如果您不需要重复 - answer here。
https://jsbin.com/dexagiresa/2/edit?js,output
let profiles = [
{
name:"1+ Adults in Household",
qualifiers: [
{
name: 'Number of adults in the household'
}
]
},
{
name: '75k',
qualifiers: [
{
name: 'Division'
},
{
name: 'Income'
}
]
},
{
name: 'Time Warner',
qualifiers: [
{
name: 'Division'
}
]
}
];
let subscription = [
"Cinemax Subscription",
"Disney Subscription",
"Encore Subscription",
"Epix Subscription",
"HBO Subscription",
"MLB Subscription",
"NBA Subscription",
"NHL Subscription",
"Division"
];
var filteredProfiles = profiles.reduce(function (collectedResults, profile) {
var newResults = profile.qualifiers.reduce(function(foundQualifiers, qualifier) {
if(subscription.indexOf(qualifier.name) > -1) {
return foundQualifiers.concat(qualifier.name);
} else {
return foundQualifiers;
}
}, []);
return collectedResults.concat(newResults);
}, []);
document.write(filteredProfiles);