如何从一组数组中删除元素,这些元素连接到 JavaScript 中的字符串?
How do I remove elements from a set of arrays with elements that are concatenated to a string in JavaScript?
我目前有这套:
Set1 = {
Alpha: [One, Two],
Beta: [One, Two, Three],
Delta: [One]
}
我也有这个元素数组:
Arr1 = [Alpha_One, Beta_One, Beta_Two, Delta_One]
我正在寻找一种方法来以编程方式删除在此集合中找到的所有元素到它各自的数组,如下所示:
Set1 = {Alpha: [Two], Beta: [Three], Delta: []}
据我所知,forEach()
方法不接受if语句,所以我不知道是否有其他方法可以做到。
找到索引拼接即可
let Set1 = {
"Alpha": ["One", "Two"],
"Beta": ["One", "Two", "Three"],
"Delta": ["One"]
};
let Arr1 = ["Alpha_One", "Beta_One", "Beta_Two", "Delta_One"];
Arr1.forEach(e=>{
let t = e.split('_');
if(Set1.hasOwnProperty(t[0])){
var index = Set1[t[0]].indexOf(t[1]);
if (index !== -1) {
Set1[t[0]].splice(index, 1);
}
}
});
console.log(Set1);
拆分你的 Arr1 并从精确的键拼接元素
const Arr1 = ['Alpha_One', 'Beta_One', 'Beta_Two', 'Delta_One'];
const Set1 = {
Alpha: ['One', 'Two'],
Beta: ['One', 'Two', 'Three'],
Delta: ['One']
};
const newArr = [];
Arr1.forEach(itemArr => {
newArr.push(itemArr.split('_'));
})
for (let key in Set1) {
newArr.forEach(itemArr => {
if (key === itemArr[0]) {
Set1[key].forEach((item, i) => {
if (item === itemArr[1]) {
Set1[key].splice(i, 1)
}
});
}
})
};
console.log(Set1)
我目前有这套:
Set1 = {
Alpha: [One, Two],
Beta: [One, Two, Three],
Delta: [One]
}
我也有这个元素数组:
Arr1 = [Alpha_One, Beta_One, Beta_Two, Delta_One]
我正在寻找一种方法来以编程方式删除在此集合中找到的所有元素到它各自的数组,如下所示:
Set1 = {Alpha: [Two], Beta: [Three], Delta: []}
据我所知,forEach()
方法不接受if语句,所以我不知道是否有其他方法可以做到。
找到索引拼接即可
let Set1 = {
"Alpha": ["One", "Two"],
"Beta": ["One", "Two", "Three"],
"Delta": ["One"]
};
let Arr1 = ["Alpha_One", "Beta_One", "Beta_Two", "Delta_One"];
Arr1.forEach(e=>{
let t = e.split('_');
if(Set1.hasOwnProperty(t[0])){
var index = Set1[t[0]].indexOf(t[1]);
if (index !== -1) {
Set1[t[0]].splice(index, 1);
}
}
});
console.log(Set1);
拆分你的 Arr1 并从精确的键拼接元素
const Arr1 = ['Alpha_One', 'Beta_One', 'Beta_Two', 'Delta_One'];
const Set1 = {
Alpha: ['One', 'Two'],
Beta: ['One', 'Two', 'Three'],
Delta: ['One']
};
const newArr = [];
Arr1.forEach(itemArr => {
newArr.push(itemArr.split('_'));
})
for (let key in Set1) {
newArr.forEach(itemArr => {
if (key === itemArr[0]) {
Set1[key].forEach((item, i) => {
if (item === itemArr[1]) {
Set1[key].splice(i, 1)
}
});
}
})
};
console.log(Set1)