从数组中的所有对象获取特定键的值 [英] Getting the values for a specific key from all objects in an array
问题描述
我正在运行一个express.js应用程序,该应用程序具有一些将数据馈送到下拉框的API.返回的数据格式为:
I'm running an express.js app that has a few apis feeding data to dropdown boxes. The data returned is in the form:
[
{
key: 'blah',
value: 'Blah Blah'
},
{
key: 'foo',
value: 'Foos'
},
{
key: 'bar',
value: 'Bars'
},
{
key: 'baz',
value: 'Bazingo'
}
];
其中key是我的选项键,value是显示文本.这个数组的结构是固定的,我知道一个事实,就是我将始终拥有键和值作为数组中每个对象的字段.
where key is my option key and value is the display text. The structure of this array is fixed and I know for a fact that I'll always have key and value as the fields in each object in the array.
当我尝试验证提交的表单(其他服务器端验证)时,我想将为字段提供的值与数组中所有键"的值(blah,foo,bar, baz).鉴于这将是一条经常使用的路由,我想避免每次都遍历数组以查找允许的值.有没有更简单的方法可以做到这一点?换句话说,我知道我可以使用:
When I try to validate the form submitted (additional server side validation), I'd like to cross-reference the value provided for a field against all the values for "key" in the array (blah, foo, bar, baz). Given that this is going to be a frequently used route, I'd like to avoid iterating over the array to find the permitted values, every single time. Is there a simpler way to do this? In other words, I know I can use:
permittedValues = [];
for (i = 0; i < array.length; i++){
permittedValues[i] = array[i]["key"];
}
但如果可能的话,我想避免这种for循环.
but I'd like to avoid this for loop, if possible.
P.S:这似乎是一个基本问题,我在网上找到的答案并不能完全回答我的问题.因此,如果已经提出并回答此问题,我们深表歉意.
P.S: This seems to be a fundamental question and the answers I found online didn't exactly answer my question. So, apologies if this has already been asked and answered.
推荐答案
您可以 map
:
permittedValues = array.map(function(value) {
return value.key;
});
在ES6/ES2015中,箭头功能:
In ES6/ES2015 it's even prettier with arrow functions:
permittedValues = array.map(value => value.key);
它可能更漂亮,但是它可能不比for()
循环快.
It might be prettier, but it's probably not faster than a for()
loop.
这篇关于从数组中的所有对象获取特定键的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!