Javascript Lodash 从对象数组中获取键值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/38284125/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 21:16:32  来源:igfitidea点击:

Lodash get key values from array of objects

javascriptarrayslodash

提问by Ceddy Muhoza

I have an arrayof objects,

我有一个arrayobjects

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"
  }...
];

I get only it's values without keys

我只得到它的值而没有 keys

Now i used this function to get the values from array like this, I pass array then it returns only values without 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('');
}

Then it returns the values data without keys like this,

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

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

Question: How can i change my foo function to lodash?

问题:如何将我的 foo 函数更改为 lodash?

回答by rpadovani

Use _.values()

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

回答by hlfcoding

out.map(_.values);

out.map(_.values);

Or if below ES5: _.map(out, _.values);

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