我怎样才能把这个 foreach push 循环变成一个 reducer 函数?

时间:2021-06-05 18:08:46

标签: javascript typescript

我目前有一个如下所示的函数:

export const getTags = (element: Record<string, any>) => {
  const tags: Record<string, any> = {};
  Object.keys(element).forEach((key: string) => {
    if (element[key] === true) {
      tags[key] = true;
    } else if (element[key] === false) {
      tags[key] = false;
    }
  });
  return tags;
};

你这样称呼它:

const objToCheck = {
  foo: true,
  bar: false,
  baz: true,
  moo: [],
  boo: "hello",
}

const tags = getTags(objToCheck);
// returns: { foo: true, bar: false, baz: true }

我目前通过创建一个空对象并推送到它的一种非常低效的方式来做到这一点,我想知道是否有一种不同的方法,例如 reduce 来正确填充这个对象?使代码更简洁。

我的函数的目的是将所有带有布尔值的值提取到一个具有相同键名和值的新对象中。

4 个答案:

答案 0 :(得分:3)

好的解决方案应该是这样的:

export const getTags = (element: Record<string, any>) => {
  return Object.fromEntries(
    Object.entries(element)
      .filter(([key,val]) => val instanceof Boolean)
  );
};

我们只是过滤掉非布尔值

答案 1 :(得分:1)

你可以这样做:

const objToCheck = {
  foo: true,
  bar: false,
  baz: true,
  moo: [],
  boo: "hello",
}

const result = Object.entries(objToCheck).reduce((acc, [key, value])=> { if([true, false].includes(value)) acc[key]=value; return acc; },{})
console.log('Result: ', result)

答案 2 :(得分:1)

试试这个

@RestController
public class Controller
{
    private static class ViewModel
    {
        private LinkedHashMap<String, Object> result = new LinkedHashMap<>();

        public LinkedHashMap<String, Object> getResult()
        {
            return result;
        }

        public void setResult(LinkedHashMap<String, Object> result)
        {
            this.result = result;
        }
    }

    @PostMapping("/fetchViewModel")
    public ViewModel fetchViewModel()
    {
        ViewModel result = new ViewModel();
        result.getResult().put("outputString", "value");
        return result;
    }

    @GetMapping("/start")
    public Mono<String> startSuccess()
    {
        return this.sendRequest("fetchViewModel", "contract", ViewModel.class, v -> (String) v.getResult().get("outputString"));
    }

    private <T, U, V> Mono<U> sendRequest(String url, T contract, Class<V> responseType, Function<V, U> transform)
    {
        WebClient webClient = WebClient.create("http://localhost:8080/");
        WebClient.ResponseSpec foo = webClient.post()
                .uri(url)
                .body(Mono.just(contract), contract.getClass())
                .retrieve();
        Mono<V> mono = foo.bodyToMono(responseType);
        Mono<U> trans = mono.map(transform);
        return trans;
    }

    @GetMapping("/startClassCastException")
    public Mono<String> startClassCastException()
    {
        return this.<String, String, ViewModel> sendRequestClassCastException("fetchViewModel", "contract", v -> (String) v.getResult().get("outputString"));
    }

    private <T, U, V> Mono<U> sendRequestClassCastException(String url, T contract, Function<V, U> transform)
    {
        ParameterizedTypeReference<T> contractType = new ParameterizedTypeReference<T>() {};
        ParameterizedTypeReference<V> responseType = new ParameterizedTypeReference<V>() {};
        WebClient webClient = WebClient.create("http://localhost:8080/");
        WebClient.ResponseSpec foo = webClient.post()
                .uri(url)
                .body(Mono.just(contract), contractType)
                .retrieve();
        Mono<V> mono = foo.bodyToMono(responseType);
        Mono<U> trans = mono.map(transform);  // ClassCastException in Lambda
        return trans;
    }
}

答案 3 :(得分:0)

修改原始对象

const getTags = obj => {
    for(const key in obj) {
        if(typeof (obj[key]) !== 'boolean' ) delete obj[key]
    }
    return obj
}

返回副本

const getTags = ({...obj}) => {
    for(const key in obj) {
        if(typeof (obj[key]) !== 'boolean' ) delete obj[key]
    }
    return obj
}