'Is there a way I can loop inside a var in typescript?
setup() {
var nodes = {
node1: { name: "Node 1" },
node2: { name: "Node 2" },
node3: { name: "Node 3" },
node4: { name: "Node 4" },
}
var edges = {
edge1: { source: "node1", target: "node2" },
edge2: { source: "node2", target: "node3" },
edge3: { source: "node3", target: "node4" },
}
return { nodes, edges }
}
So instead of writing node1,node2, and so on, is there a way I can loop and create the exact same thing? Any suggestions are appreciated.
Solution 1:[1]
Yes. You can dynamically create property names using something like Object.fromEntries.
Object.fromEntries creates an object from a series of entries, where an "entry" is an array with two elements: a property name, and a value for that property.
Here's an example that recreates your data above:
function setup() {
const nodes = Object.fromEntries(
[1,2,3,4].map(n => ["node"+n, { name: "Node " + n }])
)
const edges = Object.fromEntries(
[1,2,3].map(n => [
"edge"+n,
{ source: "node" + n, target: "node" + String(n+1) }
])
)
return { nodes, edges }
}
console.log(setup())
Solution 2:[2]
Sure you can! Many ways, one of the common ones is:
const nodes = Object.fromEntries(
Array.from(Array(10).keys())
.map(i => [`node${i + 1}`, {name: `Node ${i + 1}`}])
);
/* nodes are:
{
"node1": {
"name": "Node 1"
},
"node2": {
"name": "Node 2"
},
"node3": {
"name": "Node 3"
},
"node4": {
"name": "Node 4"
},
"node5": {
"name": "Node 5"
},
"node6": {
"name": "Node 6"
},
"node7": {
"name": "Node 7"
},
"node8": {
"name": "Node 8"
},
"node9": {
"name": "Node 9"
},
"node10": {
"name": "Node 10"
}
}
*/
Solution 3:[3]
The following code has the same result but uses for-loops, please be more specific in your question if you need something else.
setup() {
var nNodes = 4
var nEdges = 3
var nodes = {}
var edges = {}
for(i = 1 ; i < nNodes + 1; i++){
nodes['node'+i.toString()] = {"name": "Node " + i.toString()}
}
for(i = 1 ; i <nEdges + 1; i++){
edges['edge'+(i+1).toString()] = {"source": "node"+i.toString(), "target": "node"+(i+1).toString()}
}
return { nodes, edges }
}
Solution 4:[4]
Try this (I just added a logic to generate the objects) :
const nodes = {}
var edges = {}
for (let i = 1; i <= 4; i++) {
nodes['node' + i] = { name: 'Node ' + i }
if (i !== 4) {
edges['edge' + i] = { source: 'node' + i, target: 'node' + (i + 1)
}
}
}
console.log(nodes);
console.log(edges);
Solution 5:[5]
Need to loop through and append them:
foreach (range(1, 12) as $number){
$numbers[] = sprintf("%03d", $number);
}
print_r($numbers);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | David P. Caldwell |
| Solution 2 | Igor Loskutov |
| Solution 3 | Guillaume |
| Solution 4 | Rohìt JÃndal |
| Solution 5 | Wakka |
