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
Lodash get key values from array of objects
提问by Ceddy Muhoza
I have an array
of objects
,
我有一个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"
}...
];
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()
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);