W
W
webe2019-02-14 22:23:38
go
webe, 2019-02-14 22:23:38

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} // стало

I want to understand whether it is easier to work with data there or more difficult than in JS

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vladislav, 2019-02-15
@ghostiam

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

The code
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}
}

Example with interface and different types:
https://play.golang.org/p/OXUVv58YZoa
The code
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 question

Ask a Question

731 491 924 answers to any question