What I am trying to do is to create an array, whenever the element I am looking for is found (bank in my case). The first occurrence of the element should be placed in the first array and the second one in the second array and so on. Finally after all the elements are placed in separate arrays I push them onto a main array.
Is it possible to create the arrays with different names dynamically like Bank_1 ,Bank_2 and so on ?? and is this the right approach ?
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);
}
Example:
// Input:
[{ bank: "team1" }, { bank: "team2" }, { bank: "team3" }]
// Result:
{ bank_1: ["team1"], bank_3: ["team3"], bank_3: ["team3"] }
7 Answers 7
const data = [{ bank: "team1" }, { bank: "team2" }, { bank: "team3" }]
console.log(
Object.fromEntries(
data.map(
(v, i) => [`bank_${++i}`, v.bank]
)
)
)
Comments
Iterate the array with Array.map() and create an entry of [key, value] from each item, and then convert to an object with 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)
If Object.fromEntries() is not supported, you can use 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)
Comments
this will create bank names dynamically
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 Comments
Yes it is possible:
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);
1 Comment
const input = [{ bank: "team1" }, { bank: "team2" }, { bank: "team3" }];
const result = {};
input.forEach(
(item, i) => {
result[`bank_${i +1}`] = [item.bank];
}
);
console.log(result);
Comments
The map() can be used here to manipulate the object as follows:
let data = [{ bank: "team1" }, { bank: "team2" }, { bank: "team3" }];
newData = data.map((item, index) => {
return {['bank_' + index] : [item.bank]}
})
console.log(newData);
Comments
Run forEach on data and create a dynamic key using the index, see below:
let data = [{ bank: "team1" }, { bank: "team2" }, { bank: "team3" }];
let newData = {};
data.forEach((item, index) => {
newData['bank_' + (index+1)] = [item.bank];
})
console.log(newData);
bank[i] = [];is wrong.