Answer the question
In order to leave comments, you need to log in
Does GO filter map reduce some every?
Can anyone tell me how the following code will look like in GO:
var data = [{name:"width", value:100},{name:"height", value:300}] // было
var result = data.reduce((acc, {name,value}) => ({ ...acc, [name]: value}), {})
console.log(result); // {width:100, height:300} // стало
Answer the question
In order to leave comments, you need to log in
There is no "magic" in Go, and there is static typing.
All "magic" must be written in the forehead.
I rewrote your example in Go, but it will work if the type of the value field will always be int, but if there are different types, you will have to use an interface, which is not very good.
Go will not work if the data is not typed (there will be a hassle with conversion, and performance will also decrease compared to the typed approach).
https://play.golang.org/p/eGfphNwZqRR
package main
import (
"fmt"
)
func main() {
type KV struct {
Name string
Value int
}
data := []KV{
{
Name: "width",
Value: 100,
},
{
Name: "height",
Value: 300,
},
}
result := make(map[string]int)
// reduce
for _, v := range data {
result[v.Name] = v.Value
}
fmt.Printf("%#v", result) // map[string]int{"width":100, "height":300}
}
package main
import (
"fmt"
)
func main() {
type KV struct {
Name string
Value interface{}
}
data := []KV{
{
Name: "width",
Value: 100,
},
{
Name: "height",
Value: 300,
},
{
Name: "image",
Value: "cat.jpg",
},
}
result := make(map[string]interface{})
for _, v := range data {
result[v.Name] = v.Value
}
fmt.Printf("%#v", result) // map[string]interface {}{"width":100, "height":300, "image":"cat.jpg"}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question