gpt4 book ai didi

javascript - 过滤数组键

转载 作者:行者123 更新时间:2023-11-29 16:37:39 24 4
gpt4 key购买 nike

我有一个对象主体,我想从中获取键的值。如何以最少的计算量获取 membershipIdserviceIduserId

我只想要数据,只是我不想使用过滤器 3 次

var body = {
"custom_fields": [{
"label": "membership_id",
"data": "1",
}, {
"label": "service_id",
"data": "1",

}, {
"label": "user_id",
"data": "26134",
}]
};

var membershipInfo = body.custom_fields.filter(n=>{
return n.label == "membership_id";
});

var serviceInfo = body.custom_fields.filter(n=>{
return n.label == "service_id";
})
var userInfo = body.custom_fields.filter(n=>{
return n.label == "user_id";
})

var membershipId = membershipInfo[0].data;
var serviceId = serviceInfo[0].data;
var userId = userInfo[0].data;

console.log(membershipId,serviceId,userId);

最佳答案

...in minimum computations

嗯,重复循环数组并不是最小的。您将使用一个循环,可能是一个相当无聊的循环:

var membershipId, serviceId, userId;
var fields = body.custom_fields;
for (var i = 0, len = fields.length; i < len; ++i) {
var entry = fields[i];
switch (entry && entry.label) {
case "membership_id":
membershipId = entry.data;
break;
case "service_id":
serviceId = entry.data;
break;
case "user_id":
userId = entry.data;
break;
}
}

实例:

var body = {
"custom_fields": [{
"label": "membership_id",
"data": "1",
}, {
"label": "service_id",
"data": "1",

}, {
"label": "user_id",
"data": "26134",
}]
};

var membershipId, serviceId, userId;
var fields = body.custom_fields;
for (var i = 0; i < fields.length; ++i) {
var entry = fields[i];
switch (entry && entry.label) {
case "membership_id":
membershipId = entry.data;
break;
case "service_id":
serviceId = entry.data;
break;
case "user_id":
userId = entry.data;
break;
}
}

console.log(membershipId, serviceId, userId);

并不令人兴奋,但你说“以最少的计算量”。 :-)

这不是最简洁的方式,但它可能是运行时最高效的方式。您可以进行的调整:

  • 如果你知道永远不会有 nullundefined条目,您可以删除 entry &&参与switch

  • 如果有很多条目与任何情况都不匹配,如果您已获得所需的全部内容,您可能会提前停止

关于javascript - 过滤数组键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49706105/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com