簡體   English   中英

在循環中從以前的數組值創建新數組

[英]Creating new Array from previous Array values in a loop

我有一個名為組的字符串數組,我正在使用 forEach 循環遍歷它們,我想要做的是創建一個新數組,其中每個字符串都是它的名稱。

我試圖用let [group] = []創建數組,但這給出了一個標識符組已經被聲明錯誤。 任何幫助表示贊賞

代碼:

let groups = ['a','b','c']
//forEach loop creates an array for each string in groups
groups.forEach(group => {
            let [group] = []
            //Adding things to new array here
        })
//Each new array from groups is added to an object/array that is returned by the function

不要使用 forEach,reduce 適用於數組 -> 對象轉換:

const myGroups = groups.reduce((acc, group) => {
  let arr = [];
  // add stuff here
  return Object.assign({}, acc, {[group]: arr});
}, {});

這將為您提供一個對象,其中“組”值是鍵,而您創建的任何數組都是值。 如果相同的組值出現多次,則較早的值將被覆蓋。

示例代碼:

a = ['a', 'b', 'c'];
b = {};
a.forEach( x => {
    b[x] = [];
});
console.log(b);

暫無
暫無

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

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