使用lodash或JavaScript过滤此对象的最佳方法是什么?

时间:2016-06-28 17:24:19

标签: javascript node.js lodash

我有一个像这样的对象

 var result = {
    case1: {
        documents: [{
            versionSeriesId: 'BkO9EXxL',
            documentTypeId: '80',
            isDeleted: false
        }],
        answer: true
    },
    case2: {
        documents: [{
            versionSeriesId: 'BkO9EXxL',
            documentTypeId: '80',
            isDeleted: false
        }],
        answer: true
    },
    case3: {
        documents: []
    },
    case4: {
        documents: [{
            versionSeriesId: 'BkO9EXxL',
            documentTypeId: '80',
            isDeleted: false
        }],
        answer: false
    }
}

我想过滤只有 answer:true 的对象。结果应该是这样的:

{
    case1: {
        documents: [{
            versionSeriesId: 'BkO9EXxL',
            documentTypeId: '80',
            isDeleted: false
        }],
        answer: true
    },
    case2: {
        documents: [{
            versionSeriesId: 'BkO9EXxL',
            documentTypeId: '80',
            isDeleted: false
        }],
        answer: true
    }
}

我该怎么做?

3 个答案:

答案 0 :(得分:2)

只需使用Object.keys,然后使用Array.forEach方法编译新对象,即可快速完成此操作而无需外部库。

var filtered = {};
Object.keys(result).forEach(function(item) {
  if (result[item].answer === true) {
    filtered[item] = result[item];
  }
});

使用下面的代码段进行测试:

var result = {
  case1: {
    documents: [{
      versionSeriesId: 'BkO9EXxL',
      documentTypeId: '80',
      isDeleted: false
    }],
    answer: true
  },
  case2: {
    documents: [{
      versionSeriesId: 'BkO9EXxL',
      documentTypeId: '80',
      isDeleted: false
    }],
    answer: true
  },
  case3: {
    documents: []
  },
  case4: {
    documents: [{
      versionSeriesId: 'BkO9EXxL',
      documentTypeId: '80',
      isDeleted: false
    }],
    answer: false
  }
}

var filtered = {};
Object.keys(result).forEach(function(item) {
  if (result[item].answer === true) {
    filtered[item] = result[item];
  }
});

console.log(filtered);

答案 1 :(得分:2)

您可以像这样使用Lodash pickBy函数:

_.pickBy(result, function(c){return c.answer});

pickBy“创建一个由对象属性组成的对象谓词为”(docs)返回truthy。在您的示例中,您需要一个具有answer真实的案例的对象,因此谓词只返回该值。

答案 2 :(得分:0)

Object.keys()为您提供数组的键,并允许您遍历属性。然后,您可以根据您的标准过滤它们,并将正确的属性添加到新对象。

var out = {};

Object.keys(result).filter(function(item) {
    return result[item].answer === true;
}).map(function(item) {
    out[item] = result[item];
});

<强>文档