我有一个这样的对象:
{
0001: "org1",
00002: "org2",
12134: "testtest"
}
如何将其转换为这样的对象数组:
[
{ value: '0001', label: 'org1' },
{ value: '00002', label: 'org2'},
{ value: '12134', label: 'testtest' }
]
答案 0 :(得分:3)
您可以映射对象的条目并创建所需的数组:
const obj = {
'0001': "org1",
'00002': "org2",
'12134': "testtest"
};
const result = Object.entries(obj)
.map(([value, label]) => ({ value, label }));
console.log(result);
答案 1 :(得分:2)
您可以使用array.prototype.map
和Object.entries
:
var o = {
"0001": "org1",
"00002": "org2",
"12134": "testtest"
};
var res = Object.entries(o).map(([value, label]) => ({value, label}));
console.log(res);
答案 2 :(得分:0)
您可以使用lodash的transform功能
var obj = {
"0001": "org1",
"00002": "org2",
"12134": "testtest"
};
var res = _.transform(obj, function (res, val, key) {
res.push({
value: key,
label: val
});
}, []);
console.log(res);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.10/lodash.min.js"></script>