JavaScript新手并尝试学习!我正在尝试通过两个对象数组进行映射,如果某个属性匹配,则将特定信息放入一个数组中。
extension MyView: UITextFieldDelegate {
func textFieldDidEndEditing(_ textField: UITextField) {
//Do you check here
}
}
如果arrNames.name == arrInfo.name,我希望结果等于arrInfo.info。
我尝试过的:
let result;
let arrNames = [{
name: "A"
}, {
name: "B"
}, {
name: "C"
}]
let arrInfo = [{
name: "A",
info: "AAA"
}, {
name: "B",
info: "BBB"
}, {
name: "C",
info: "ccc"
}]
^这显然不起作用-但我想知道Assign还是Filter是否合适。
在此先感谢您的帮助(很抱歉这可能是骗子)!
答案 0 :(得分:1)
您可以在find()内使用map()查找元素。即使两个数组中的索引都不相同,也会找到该元素。
然后使用filter()过滤任何undefined
值,如果没有匹配项,这些值将出现。
var arrNames = [
{name: "A"},
{name: "B"},
{name: "C"}
];
var arrInfo = [
{name: "A", info: "AAA"},
{name: "B", info: "BBB"},
{name: "C", info: "ccc"}
];
let result = arrNames.map(x => {
item = arrInfo.find(item => item.name === x.name);
if (item) {
return item.info;
}
}).filter(item => item !== undefined); // Can also use filter(item => item);
console.log(result);
答案 1 :(得分:0)
您可以使用带有内部条件的地图
el.name === arrNames[index].name && el.info
手段:
if (el.name === arrNames[index].name) return el.info
let arrNames = [{
name: "A"
}, {
name: "B"
}, {
name: "C"
}]
let arrInfo = [{
name: "A",
info: "AAA"
}, {
name: "B",
info: "BBB"
}, {
name: "C",
info: "ccc"
}]
const res = arrInfo.map((el, index) => el.name === arrNames[index].name && el.info)
console.log(res)
答案 2 :(得分:0)
let result = [];
arrNames = [
{name: "A"},
{name: "B"},
{name: "C"},
]
arrInfo = [
{name: "A", info: "AAA"},
{name: "B", info: "BBB"},
{name: "C", info: "ccc"},
]
result = arrNames.map(function(_, index){
if(arrNames[index].name === arrInfo[index].name) {
return arrInfo[index].info
}
})