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
209 views
in Technique[技术] by (71.8m points)

javascript - Array transformation/manipulation

I have one array like this one:

array1=[{value:1, label:'value1'},{value:2, label:'value2'}, {value:3, label:'value3'}]

I have a second array of integer :

array2=[1,3]

I would like to obtain this array without a loop for :

arrayResult = ['value1', 'value3']

Does someone know how to do it with javascript ?

Thanks in advance

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

Map the elements in array2 to the label property of the element in array1 with the corresponding value:

array2                      // Take array2 and
  .map(                     // map
    function(n) {           // each element n in it to
      return array1         // the result of taking array1
        .find(              // and finding
          function(e) {     // elements
            return          // for which 
              e.value       // the value property
              ===           // is the same as 
              n;            // the element from array2
          }
        )
        .label              // and taking the label property of that elt
      ;
    }
  )
;

Without comments, and in ES6:

array.map(n => array1.find(e => e.value === n).label);

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

...