简体   繁体   English

如何将此 foreach 推送循环变成减速器 function?

[英]How can I turn this foreach push loop into a reducer function?

I currently have a function that looks like this:我目前有一个看起来像这样的 function:

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;
};

You call it like this:你这样称呼它:

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

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

I currently do this with quite an inefficient way by making an empty object and pushing to it, I was wondering if there was a different method like reduce to fill this object properly?我目前通过制作一个空的 object 并推动它以一种非常低效的方式来做到这一点,我想知道是否有不同的方法,比如reduce来正确填充这个 object? Making the code a bit more clean.使代码更干净。

The purpose of my function is to extract all values with booleans to a new object with the same key names and values.我的 function 的目的是将所有带有布尔值的值提取到具有相同键名和值的新 object 中。

good solution should look something like this:好的解决方案应该是这样的:

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

we just filter out nonboolean values我们只是过滤掉非布尔值

You can do it like this:你可以这样做:

 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)

Try this尝试这个

export const getTags = (element: Record < string, any > ) => Object.entries(element).reduce((acc, [key, val]) => {
    if (typeof key === "boolean") {
        acc[key] = val;
    }
    return acc;
}, {});

To modify the original object修改原object

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

To return a copy退回副本

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM