JS-在没有下划线的情况下获取过滤后的值的对象键值对

时间:2018-08-02 15:08:23

标签: javascript

我有一个用true / false过滤对象值的问题,就像在本主题Get object keys for filtered values中一样,但是没有下划线,意味着仅使用纯JS。关于StackOverflow或多或少有类似的问题,但不幸的是,我未能设定一种可行的方法。

例如,我有一个对象:

var anObject = {first_property: false, second_property: true, third_property: false, fourth_property: false, fifth_property: false, sixth_property: true, seventh_property: false, eight_property: nine-nth_property: false}

我需要获取一个仅具有真实值的新对象,例如:

var newObject = { second_property: true, sixth_property: true }

要过滤,我编写了以下过滤器:

function isValid(value) {
    if (typeof value === "undefined" || value == null || value.length == 0 || value == false) {
        return false;
    } else {
        return true;
    }
}

摇了摇头,花了几个小时尝试不同的方法,但是结果并不令人满意。我应该如何构建算法来做到这一点,在这里值得使用哪些自定义/开箱即用的功能?预先感谢!

4 个答案:

答案 0 :(得分:4)

您需要遍历键/值对,找出true。该解决方案的工作原理如下:

  1. 使用Object.entries从对象获取键/值对。
  2. 使用Array.reduce遍历条目。
  3. 在每次迭代中,检查值是否为true。如果是这样,则将键/值对添加到结果中。

var obj = {
  first_property: false,
  second_property: true,
  third_property: false,
  fourth_property: false,
  fifth_property: false,
  sixth_property: true,
  seventh_property: false
};

var res = Object.entries(obj)
  .reduce((result, [key, value]) => {
    if (value) {
      result[key] = value;
    }

    return result;
  }, {})

console.log(res);

答案 1 :(得分:2)

有几种方法可以使用Object.entries()Object.keys(),不同的数组方法等,但我想我会提供一种。将键向下过滤到值为true的键,然后将这些键添加到output

var obj = {
  first_property: false,
  second_property: true,
  third_property: false,
  fourth_property: false,
  fifth_property: false,
  sixth_property: true,
  seventh_property: false
};

var output = {};

Object.keys(obj)                                  //Get all keys from the object ['first_property', 'second_property', ...]
    .filter((key) => obj[key])                    //Filter the list of keys down to only those where their value is true
    .forEach((key) => output[key] = obj[key]);    //For each key in our filtered list, add it to the output object

console.log(output);

答案 2 :(得分:2)

还可以通过减少Object.keys数组(不进行其他过滤)来实现:

Object.keys(obj).reduce((acc, key) => 
  ((obj[key] ? acc[key] = obj[key] : null), acc)
, {});

// {second_property: true, sixth_property: true}

还有一个简短的版本:

Object.keys(obj).reduce((acc, key) => (obj[key] && (acc[key] = obj[key]), acc), {});

答案 3 :(得分:1)

您可以过滤(Array.prototype.filter)真实键,并使用以下键创建新对象(Array.prototype.reduce):

var obj = {first_property: false,second_property: true,third_property: false,fourth_property: false,fifth_property: false,sixth_property: true,seventh_property: false};    

var result = Object.keys(obj).filter(k => obj[k]).reduce((a,k) => (a[k] = obj[k], a), {});

console.log(result);