我将使用forOwn迭代对象的属性并手动创建一个数组,并且无法帮助认为已经有一个oneliner已经可用.
{
prop1 : "value",
prop2: { sub:1}
}
至:
[
{key: "prop1", value: "value"},
{key: "prop2", value: {sub:1}}
]
谢谢
解决方法:
你可以使用lodash的_.map()和shorthand property names:
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>
或者你可以使用Array.map()
和Array.map()
和array destructuring来做到这一点:
const obj = {
prop1 : "value",
prop2: { sub:1}
};
const result = Object.entries(obj).map(([prop, value]) => ({ prop, value }));
console.log(result);