I want to assign all the array elements as the keys of hash table. For Example...
# arrays
$k=@(1,2,3)
$v=@("one","two","three")
# hashtable
$table=@{}
I want output like this:
$table={1="one",2="two",3="three"}
Is there any way to do it?
0..($k.count-1) |
Foreach-Object -Begin {
$table=[ordered]@{}
} -process {
$table.Add($k[$_],$v[$_])
}
Assuming each array is the same size, you can loop through your indexes and grab elements at the same index from both arrays. The Add(key,value) method adds new key-value pairs to your hash table.
You can also accomplish this with a for each loop to be able to easily track the index between both arrays
$k = @(1, 2, 3)
$v = @("one", "two", "three")
$table = @{}
for ($i=0; $i -lt $k.Length; $i++){
$table[$k[$i]] = $v[$i]
}
Note: this is also somtimes referred to as "zipping" two arrays