Javascript lodash - 项目/转换对象为键值数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/32100692/
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 - project/transform object into key value array
提问by sambomartin
I'm about to use forOwn
to iterate through an object's properties and create an array manually and can't helping thinking there's a oneliner already available to do it.
我将要使用forOwn
迭代对象的属性并手动创建一个数组,并且不禁想到已经有一个 oneliner 可以做到这一点。
{
prop1 : "value",
prop2: { sub:1}
}
to:
到:
[
{key: "prop1", value: "value"},
{key: "prop2", value: {sub:1}}
]
Thanks
谢谢
回答by Ori Drori
You can use lodash's _.map()with shorthand property names:
您可以将 lodash 的_.map()与速记属性名称一起使用:
const obj = {
prop1 : "value",
prop2: { sub:1}
};
const result = _.map(obj, (value, prop) => ({ prop, value }));
console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.2/lodash.min.js"></script>
Or you can do it using Object#entries
with Array.map()
and array destructuring:
或者你可以使用Object#entries
withArray.map()
和array destructuring来做到这一点:
const obj = {
prop1 : "value",
prop2: { sub:1}
};
const result = Object.entries(obj).map(([prop, value]) => ({ prop, value }));
console.log(result);
回答by Joseph
You don't even need lodash for that:
你甚至不需要 lodash:
var arr = Object.keys(obj).map(function(key){
return { key: key, value: obj[key] };
});
回答by Dzianis Sudas
A little bit of ES6 :
一点点 ES6 :
_.map( obj, (value, key) => ({key,value}) )
_.map( obj, (value, key) => ({key,value}) )
回答by Marcelo Lazaroni
If you are using lodash/fpyou can use _.entries
如果您使用的是lodash/fp,则可以使用_.entries
const a = { one: 123, two: { value: 'b' }};
const pairs = _.entries(a).map(p => ({ key:p[0], value: p[1] }))
console.log(pairs)
// [
// {
// "key": "one",
// "value": 123
// },
// {
// "key": "two",
// "value": {
// "value": "b"
// }
// }
// ]
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.15.0/lodash.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash-fp/4.15.0/lodash-fp.js"></script>
回答by Skarllot
You can use pairs
if it fits your case:
pairs
如果它适合您的情况,您可以使用:
_.pairs({ 'barney': 36, 'fred': 40 });
// → [['barney', 36], ['fred', 40]]
回答by sambomartin
In response to Ori's comment and for completeness, I've posted the _.forOwn version. It's marginally faster but you need to declare the array first (not-a-one-liner).
为了回应 Ori 的评论并为了完整性,我发布了 _.forOwn 版本。它稍微快一点,但您需要先声明数组(非单行)。
var arr = [];
_.forOwn(obj,function(item, key) {
arr.push({ property : key, value : item});
});