简体   繁体   中英

What is the best way to filter this object using lodash or JavaScript?

I am having an object like this

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

I want to filter the object which is having the answer:true only. The result should be like this:

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

How can I do this?

You can do this quickly and without the need for an external library just by using Object.keys and then use the Array.forEach method to compile a new object.

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

Test with the snippet below:

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

You can use the Lodash pickBy function like this:

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

pickBy "creates an object composed of the object properties predicate returns truthy for" ( docs ). In your example, you want an object with the cases for which answer is truthy, so the predicate just returns that value.

Object.keys() gives you the keys of your array and allows you to iterate through the properties. Then you can filter them based on your criterion and add the correct properties to a new object.

var out = {};

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

Docs

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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