Lodash从对象数组中获取键值

时间:2016-07-09 16:54:32

标签: javascript arrays lodash

我有array objects

var out = [{
    "type": "1",
    "from": "13052033555",
    "to": "4444444",
    "amount": "40000",
    "date": 1461575799,
    "status": "1"
  }, {
    "type": "2",
    "from": "13052033555",
    "to": "1111111",
    "amount": "30000",
    "date": 1461575884,
    "status": "1"
  }...
];

我只获得没有keys

的值

现在我用这个函数从这个数组中获取值, 我传递数组然后只返回没有键的值

function foo(a) {
  var values = [];
  for (var i = 0; i < a.length; i++) {
    var obj = a[i];
    var arr = Object.keys(obj).map(function(k) {
      return obj[k]
    });
    values.push("[" + arr + "],");
  }
  return values.join('');
}

然后它返回没有这样的键的值数据,

[ ["1","13052033555","4444444","40000",1461575799,"1"],
  ["2","13052033555","1111111","30000",1461575884,"1"],
    ....]

问题:如何将我的foo功能更改为lodash?

2 个答案:

答案 0 :(得分:13)

使用_.values()

    var out = [{
        "type": "1",
        "from": "13052033555",
        "to": "4444444",
        "amount": "40000",
        "date": 1461575799,
        "status": "1"
      }, {
        "type": "2",
        "from": "13052033555",
        "to": "1111111",
        "amount": "30000",
        "date": 1461575884,
        "status": "1"
      }
    ];

    for (var i = 0; i < out.length; i++) {
      out[i] = _.values(out[i]);
    }
    

console.log(out)
<script src="https://cdn.jsdelivr.net/lodash/4.13.1/lodash.min.js"></script>

答案 1 :(得分:5)

out.map(_.values);

或者如果低于ES5:_.map(out, _.values);