簡體   English   中英

如何將變量的值作為鍵或參數傳遞給大括號內的變量?

[英]How to pass value of a variable as a key or parameter to a variable inside curly brackets?

如何將變量傳遞給數組鍵,其中數組是大括號內的另一個變量。 在以下代碼中,如果值大於 50,我將嘗試從源數組中推送值。

render(){
  var source_arr = [35,45,50,60,20];
  var dest_array = [];
  for(var x=0; x<source_arr.length; x++){
    if(source_array[x]>50){
      dest_array.push({source_array[x]});
    }
  }
  return(
    <div>
    </div>
  )
}

在這里,我無法將變量“x”的值作為 for 循環內的數組鍵傳遞。

您需要使用[]來定義鍵

render(){
  var source_arr = [];
  var dest_array = [];
  for(var x=0; x<source_arr.length; x++){
    if(a condition){
      dest_array.push({[source_array[x]]:source_array[x] });
    }
  }
  return(
    <div>
    </div>
  )
}

如果條件為真或假,您似乎想將源數組中的所有項目 map 到對象:

 const source_arr = [ {name:'hi',age:22}, {name:'bye',age:88}, ]; const dest_arr = source_arr.map( //map item to object or false item => item.age<40 && { [item.name]: item.age } ).filter(x => x); //remove all false items console.log(dest_arr);

您可以將 map 和過濾器合二為一:

 const source_arr = [ { name: 'hi', age: 22 }, { name: 'bye', age: 88 }, ]; const dest_arr = source_arr.reduce( (result, item) => //add object if condition is true item.age < 40? result.concat({ [item.name]: item.age }): result, [] ); console.log(dest_arr);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM