我一直在搜索,但遇到的所有内容都是在HTML中循环,因此我需要在.ts中循环。
我有一个数组,需要遍历并检查输入的值是否与键匹配。如果是这样,则返回数组内的值
data: any = {
'1234': {
site: 'https://example1.com/',
path: 'uploads',
link: 'https://example1.com/uploads',
},
'5678': {
site: 'https://example2.com/',
path: 'uploads',
link: 'https://example2.com/uploads',
}
}
我一直在尝试以下各种变化,但效果有限。我可以打印密钥,但无法获取值(位置,路径,链接)
let pin = '1234';
Object.keys(data).forEach(key => {
if(key == pin) {
Object.keys(key).forEach(k => {
// I'm trying to get something like k.url so I can store it
console.log(k.url);
});
}
});
答案 0 :(得分:0)
您只能使用一个循环来实现这一目标
const pin = '1234';
Object.keys(data).forEach(key => {
if(key == pin) {
console.log(data[key].url);
console.log(data[key].site);
console.log(data[key].path);
}
});
答案 1 :(得分:0)
const data = {
'1234': {
site: 'https://example1.com/',
path: 'uploads',
link: 'https://example1.com/uploads',
},
'5678': {
site: 'https://example2.com/',
path: 'uploads',
link: 'https://example2.com/uploads',
}
}
const pin = '1234';
const properties = { ...data[pin] };
Object.values(properties).forEach(v => console.log(v));
// This will NOT throw an exception
// Using a non-existing key here
Object.values({...data['fake']}).forEach(v => console.log(v));
// This will throw an exception
// Using a non-existing key here
Object.values(data['fake']).forEach(v => console.log(v));
这可以执行您想要的操作,并且仅使用一个循环。我使用了传播语法来防止未定义。如果您要查找的键不存在,则会返回一个空数组。