Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
152 views
in Technique[技术] by (71.8m points)

javascript - Getting the values for a specific key from all objects in an array

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'
    }
];

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.

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"];
 }

but I'd like to avoid this for loop, if possible.

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You could map:

permittedValues = array.map(function(value) {
  return value.key;
});

In ES6/ES2015 it's even prettier with arrow functions:

permittedValues = array.map(value => value.key);

It might be prettier, but it's probably not faster than a for() loop.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...