javascript对象骨架
var users = {};
users = {
'123': {
name: 'Lucky',
gender: 'female'
},
'456': {
name: 'K',
gender: 'male'
}
}
要求:我想通过搜索键(例如123)来检索123及其对象
'123':
{ name: 'Lucky',
gender: 'female' }
类似地,如果密钥为456,我想检索
'456':
{ name: 'K',
gender: 'male' }
}
答案 0 :(得分:0)
仅检查属性是否存在,如果存在,则将其返回:
var users = {};
users = {
'123': {
name: 'Lucky',
gender: 'female'
},
'456': {
name: 'K',
gender: 'male'
}
};
const search = s => s && users[s] && {[s]: users[s]}
console.log(search('123'))
答案 1 :(得分:0)
真的很简单-使用数组符号:
const users = {
'123': {
name: 'Lucky',
gender: 'female'
},
'456': {
name: 'K',
gender: 'male'
}
}
const getObjectByNum = n => ({ [n]: users[n] }) || "Not found";
console.log(getObjectByNum(123));
console.log(getObjectByNum(456));
.as-console-wrapper { max-height: 100% !important; top: auto; }
答案 2 :(得分:0)
您的意思是动态属性访问?为此使用[]表示法。
Inn Javascript,要访问对象的属性“ xyz”,有两种表示法:
obj.xyz
和
ob['xyz']
var users = {
'123': {
name: 'Lucky',
gender: 'female'
},
'456': {
name: 'K',
gender: 'male'
}
}
function getUserById(usermap, id) {
try {
return { [id]: usermap[id] }
} catch (error) {
console.log(error);
}
}
console.log(getUserById(users, '456'));