如何在JavaScript中动态创建数组/数组名

时间:2019-11-23 18:08:53

标签: javascript arrays

我想做的就是每当找到要查找的元素时创建一个数组(以我的情况为例)。元素的第一次出现应放置在第一个数组中,第二个出现在第二个数组中,依此类推。最后,在将所有元素放置在单独的数组中之后,我将它们推入主数组。

是否可以动态创建具有不同名称的数组,例如Bank_1,Bank_2等?这是正确的方法吗?

var bankcontainer = [];
var bank = [];

for (let i = 0; i < length ;i++)
{
 let bankname = data.periods[0].decisions[i].bank;
  bank[i] = [];
  bank[i].push(bankname);
  bankcontainer.push(bank);
}

示例:

// Input:    
[{ bank: "team1" }, { bank: "team2" }, { bank: "team3" }]

// Result:
{ bank_1: ["team1"], bank_3: ["team3"], bank_3: ["team3"] }

7 个答案:

答案 0 :(得分:3)

const data = [{ bank: "team1" }, { bank: "team2" }, { bank: "team3" }]

console.log(
  Object.fromEntries(
    data.map(
      (v, i) => [`bank_${++i}`, v.bank]
    )
  )
)

答案 1 :(得分:1)

使用Array.map()迭代数组,并从每个项目创建[key,value]的条目,然后使用Object.fromEntries()转换为对象:

const data = [{ bank: "team1" }, { bank: "team2" }, { bank: "team3" }]

const result = Object.fromEntries(
  data.map((o, i) => [`bank_${i + 1}`, o.bank])
)

console.log(result)

如果不支持Object.fromEntries(),则可以使用Array.reduce()

const data = [{ bank: "team1" }, { bank: "team2" }, { bank: "team3" }]

const result = data.reduce((r, o, i) => {
  r[`bank_${i + 1}`] = o.bank;

  return r;
}, {})

console.log(result)

答案 2 :(得分:0)

这将动态创建银行名称

var bankcontainer = [];
var bank = [];

for (let i = 0; i < length ;i++)
{
  let bankname = data.periods[0].decisions[i].bank;
  const bank["bank_" + i] = [];
  bank["bank_" + i].push(bankname);
  bank = bank["bank_" + i];
}
bankcontainer.push(bank);

答案 3 :(得分:0)

是的,有可能:

const myBanks = {};
const banks = ['BofA', 'Goldman Sachs', 'Stackoverflow Credit Union', 'Chase', 'Captial One 360'];

for (let i = 0; i < banks.length; i++)
{
  myBanks['Bank_' + i] = [banks[i]];
}

console.log(myBanks);

答案 4 :(得分:0)

const input = [{ bank: "team1" }, { bank: "team2" }, { bank: "team3" }];
const result = {};
input.forEach(
    (item, i) => { 
        result[`bank_${i +1}`] = [item.bank]; 
    }
);
console.log(result);

答案 5 :(得分:0)

map()可在此处用于如下操作对象:

let data = [{ bank: "team1" }, { bank: "team2" }, { bank: "team3" }];

newData = data.map((item, index) => {
return {['bank_' + index] : [item.bank]}
})

console.log(newData);

答案 6 :(得分:0)

对数据运行forEach并使用索引创建动态键,请参见下文:

    let data = [{ bank: "team1" }, { bank: "team2" }, { bank: "team3" }];
    let newData = {};
     data.forEach((item, index) => {
    newData['bank_' + (index+1)] = [item.bank];
    })

    console.log(newData);