如何使用lodash或javascript过滤对象

时间:2016-06-28 10:28:36

标签: javascript arrays node.js lodash

我从服务器获得这样的对象,

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

我想从对象中过滤typeId,我期待的结果是

[81,82]

任何人都可以帮忙解决这个问题。

9 个答案:

答案 0 :(得分:3)

如果您的示例中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)




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




答案 1 :(得分:2)

只需一行代码即可完成此操作:

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

这将产生:

["81", "82"]

答案 2 :(得分:0)

您可以这样做:

  1. 以某种方式访问​​每个对象,您可以使用相同的表达式。 for...in将帮助您获取对象的键,并且可以使用data[key]来获取对象。
  2. 现在,一旦我们有了对象,我们就知道在哪里看obj.documents。现在文档是一个数组,我们需要在其中的每个对象中获取TypeId。为此,您可以拥有一个数组并手动推送值,也可以使用Array.map
  3. 现在,如果您使用.map,它将为每个对象返回一个数组。因此,您必须使用array.concat将其附加到相同的函数。但是,如果您使用.push,请跳过此步骤。
  4. For..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)
    
    
    

答案 3 :(得分:0)

这会给你预期的结果,但不确定你会对它感到满意吗

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

答案 4 :(得分:0)

试试这个

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

答案 5 :(得分:0)

如果属性“文档”始终只有一个对象,请使用_.compact(_.map(data, 'documents[0].TypeId'));

如果属性“文档”包含许多对象,请使用_.flatten(_.map(data, (item) => _.map(item.documents, 'TypeId')));

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

答案 6 :(得分:0)

以下是之前答案的另一个简化版本(没有缩小花式仅填充地图):

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' ]

答案 7 :(得分:0)

您可以使用lodash的_.map函数来获得所需的结果。以下是示例代码 -

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

    return ''
}

答案 8 :(得分:0)

在lodash中解决此问题的最简单方法是使用flatMap()获取展平数组documentsmap()以获取所有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>
&#13;
&#13;
&#13;

使用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

&#13;
&#13;
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);
&#13;
&#13;
&#13;