我有一个数组的对象,
customer1 = [
{"key": "name",
"value": "Peter"},
{"key": "age",
"value": 23},
{"key": "address",
"value": "xyz St, abcd"},
{"key": "points",
"value": 234}
]我想从这个对象中找出年龄和地址,推荐的和最佳的方法是什么?对于真正的应用程序,我可能在这个数组中有20-40个键值对象,其中我可能想要访问5-10个值。
我现在所做的就是循环这个对象,并使用条件来查找和赋值给我的变量。但是在这种方法中,我必须编写多个if表达式(5-10)。
例如,
let name: string;
let points: number;
for (var item of customer1) {
if (item.key === "name") {
name = item.value;
} else if (item.key === "points") {
points = item.value;
}};发布于 2022-11-04 07:07:03
您可以在Array.filter()和Array.map()方法的帮助下实现这一需求。
现场演示
const customer1 = [
{ "key": "name", "value": "Peter" },
{ "key": "age", "value": 23 },
{ "key": "address", "value": "xyz St, abcd" },
{ "key": "points", "value": 234 }
];
const searchKeys = ['age', 'address'];
const res = customer1.filter(obj => searchKeys.includes(obj.key)).map(({ value}) => value);
const [age, address] = res;
console.log(age);
console.log(address);
发布于 2022-11-03 16:15:09
你总是要显式地写"name","points",.因为您不能解析字符串值并使用它来标识同名变量。但是,为了避免使用多个其他语句,如果,也许开关case语句更合适和更易读?
interface CustomerProperty {
key: string,
value: string | number
}
let customer1: CustomerProperty[] = [
{
"key": "name",
"value": "Peter"
},
{
"key": "age",
"value": 23},
{
"key": "address",
"value": "xyz St, abcd"},
{
"key": "points",
"value": 234
}
];
let nameValue: string;
let pointsValue: number;
for (var item of customer1) {
switch (item.key) {
case "name":
nameValue = item.value as string;
break;
case "points":
pointsValue = item.value as number;
break;
}
};https://stackoverflow.com/questions/74305929
复制相似问题