简体   繁体   English

如何使用lodash或javascript过滤对象

[英]How to filter the object using lodash or javascript

I am getting object like this from the Server, 我正在从服务器获取这样的对象,

var data = {
  test1: {
    documents: []
  },
  test2: {
    documents: [{
      vId: 'sdfas23',
      TypeId: '81',
      isDeleted: false
    }],
    answer: true
  },
  test3: {
    documents: [{
      vId: 'H1mJinyI',
      TypeId: '82',
      isDeleted: false
    }],
    answer: true
  }
}

i want to filter the typeId from the object, The Result i am Expecting is 我想从对象中过滤typeId,我期望的结果是

[81,82]

can anybody help on this. 有人可以帮忙吗

In case you have only one or zero objects in documents like in your example you can use reduce() with Object.keys() 如果您的documents只有一个或零个对象(例如您的示例),则可以将reduce()Object.keys()

 var data = {"test1":{"documents":[]},"test2":{"documents":[{"vId":"sdfas23","TypeId":"81","isDeleted":false}],"answer":true},"test3":{"documents":[{"vId":"H1mJinyI","TypeId":"82","isDeleted":false}],"answer":true}} var result = Object.keys(data).reduce(function(a, e) { if (data[e].documents[0]) a.push(data[e].documents[0].TypeId); return a; }, []) console.log(result) 

For multiple objects in documents array you can add forEach loop to previous code so you get this (there are two objects in test3.documents ) 对于documents数组中的多个对象,您可以在前面的代码中添加forEach循环,以便您可以做到这一点( test3.documents有两个对象)

 var data = {"test1":{"documents":[]},"test2":{"documents":[{"vId":"sdfas23","TypeId":"81","isDeleted":false}],"answer":true},"test3":{"documents":[{"vId":"H1mJinyI","TypeId":"82","isDeleted":false},{"vId":"Random","TypeId":"100","isDeleted":false}],"answer":true}} var result = Object.keys(data).reduce(function(a, e) { if (data[e].documents.length) data[e].documents.forEach(function(p) { a.push(p.TypeId); }); return a; }, []) console.log(result); 

You could do this with just a single line of code: 您可以只用一行代码来完成此操作:

_.map(_.flatten(_.map(_.values(data), 'documents')), 'TypeId');

This will produce: 这将产生:

["81", "82"]

You can do something like this: 您可以执行以下操作:

  1. Get access to every object in a way, you can use same expression for it. 以某种方式获得对每个对象的访问权限,可以对其使用相同的表达式。 for...in will help you get keys of an object and you can use data[key] to get object. for ... in将帮助您获取对象的键,并且可以使用data[key]来获取对象。
  2. Now once we have object, we know where to look ie obj.documents . 现在有了对象后,我们便知道在哪里查找obj.documents Now documents is an array and we need to get TypeId in every object in it. 现在文档是一个数组,我们需要在其中的每个对象中获取TypeId For this, you can have an array and manually push value in it or you can use Array.map . 为此,您可以拥有一个数组并在其中手动推送值,也可以使用Array.map
  3. Now if you use .map , it will return an array for every object. 现在,如果您使用.map ,它将为每个对象返回一个数组。 So you will have to use array.concat to append it to same function. 因此,您将必须使用array.concat将其附加到相同的函数。 But if you use .push , then skip this step. 但是,如果使用.push ,则跳过此步骤。

For..in + .map + .concat 对于..in + .map + .concat

 var data={test1:{documents:[]},test2:{documents:[{vId:"sdfas23",TypeId:"81",isDeleted:!1}],answer:!0},test3:{documents:[{vId:"H1mJinyI",TypeId:"82",isDeleted:!1}],answer:!0}}; var r = []; for(var k in data){ r = r.concat(data[k].documents.map(function(o){return o.TypeId})); } console.log(r) 

This gives you the expected result, though not sure will you be happy with it 这给了您预期的结果,尽管不确定您是否会满意

var data=  { 
    test1: { documents: [] },
    test2: { documents: [{ vId: 'sdfas23',
          TypeId: '81',
          isDeleted: false }], answer: true },
    test3:
     { documents:
        [{ vId: 'H1mJinyI',
          TypeId: '82',
          isDeleted: false }],
       answer: true } 
} 

function getIds(array) {
    var ret = [];
    for (key in data) {
        for (key2 in data[key].documents) {
            ret.push(data[key].documents[key2].TypeId)
         }
    }
    return ret
}

console.log(getIds(data));

Try this 尝试这个

Object.getOwnPropertyNames(data).map(function(val, key) {    
    return data[val].documents[0] ? data[val].documents[0].TypeId : '';    
})

If property "documents" always have only one object, just use _.compact(_.map(data, 'documents[0].TypeId')); 如果属性“ documents”始终只有一个对象,则只需使用_.compact(_.map(data, 'documents[0].TypeId'));

If property "documents" have many objects, use _.flatten(_.map(data, (item) => _.map(item.documents, 'TypeId'))); 如果属性“ documents”有很多对象,请使用_.flatten(_.map(data, (item) => _.map(item.documents, 'TypeId')));

Example - https://jsfiddle.net/qvkctvho/1/ 示例-https://jsfiddle.net/qvkctvho/1/

Here is another simplified version of the previous answers(no reduce and fancy stuff only map ) : 这是先前答案的另一个简化版本(没有reducefancy的东西仅映射):

var data=  { test1: { documents: [] },
             test2: { documents: [{ vId: 'sdfas23', TypeId: '81', isDeleted: false },{ vId: 'sdfas23', TypeId: '85', isDeleted: false }], answer: true },
             test3: { documents: [{ vId: 'H1mJinyI', TypeId: '82', isDeleted: false }], answer: true } 
};

var getTypeIds = function(data){
    var ids = [];
   // get object keys in this case : test1,test2,test3
    Object.keys(data).map(function(key){        
        // loop through each document attribute and extract TypeId attributes
        data[key].documents.map(function(item){                                                
                                    ids.push(item.TypeId);                                    
                                });


    })
    return ids;   
}

console.log(getTypeIds(data)); // [ '81', '85', '82' ]

You can use _.map function of lodash to get the result you want. 您可以使用lodash的_.map函数获取所需的结果。 Here is the sample code - 这是示例代码-

var result = _.map(data, function(v,i){
    if(_.isArray(v.documents)) {
        return v.documents[0].TypeId
    }

    return ''
}

The easiest way to solve this in lodash is by using flatMap() to get a flattened array of documents and map() to get all TypeId . 在lodash中解决此问题的最简单方法是使用flatMap()获取平整的documents数组,并使用map()获得所有TypeId

var result = _(data)
.flatMap('documents')
.map('TypeId')
.value();

 var data = { test1: { documents: [] }, test2: { documents: [{ vId: 'sdfas23', TypeId: '81', isDeleted: false }], answer: true }, test3: { documents: [{ vId: 'H1mJinyI', TypeId: '82', isDeleted: false }], answer: true } }; var result = _(data) .flatMap('documents') .map('TypeId') .value(); console.log(result); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.13.1/lodash.js"></script> 

A plain JS solution with ES6 should be something like this: 使用ES6的普通JS解决方案应该是这样的:

var result = Object.keys(data) // get keys as reference when mapping
.map(v => data[v].documents || []) // get all documents
.reduce((x, y) => x.concat(y)) // flatten
.map(v => v.TypeId); // get TypeId

 var data = { test1: { documents: [] }, test2: { documents: [{ vId: 'sdfas23', TypeId: '81', isDeleted: false }], answer: true }, test3: { documents: [{ vId: 'H1mJinyI', TypeId: '82', isDeleted: false }], answer: true } }; var result = Object.keys(data) .map(v => data[v].documents || []) .reduce((x, y) => x.concat(y)) .map(v => v.TypeId); console.log(result); 

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

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