var enums = {
'1': 'HELLO',
'2' : 'BYE',
'3' : 'TATA'
};
我希望能够将其转换为如下所示的数组,
[
{
number:'1',
word:'HELLO'
},
{
number:'2',
word:'BYE'
},
{
number:'3',
word:'TATA'
}
]
我看到的所有解决方案都由键或值组成一个数组。
答案 0 :(得分:1)
您可以使用Object.entries和map将其设置为所需格式
var enums = {
'1': 'HELLO',
'2' : 'BYE',
'3' : 'TATA'
};
let op = Object.entries(enums).map(([key, value]) => ({ number:key, word:value }))
console.log(op)
答案 1 :(得分:1)
您可以使用short hand properties映射条目。
var enums = { 1: 'HELLO', 2: 'BYE', 3: 'TATA' },
objects = Object.entries(enums).map(([number, word]) => ({ number, word }));
console.log(objects);
.as-console-wrapper { max-height: 100% !important; top: 0; }
答案 2 :(得分:1)
您可以将Object.entries()与foreach结合使用,并将其推入这样的数组
var enums = {
'1': 'HELLO',
'2' : 'BYE',
'3' : 'TATA'
};
var enumArray = []
Object.entries(enums).forEach(([key, value]) => enumArray.push({number : key, word : value}));
console.log(enumArray);
答案 3 :(得分:0)
需要创建一个Map类型的对象,然后使用get获取值 像outData.get(“ 1”)
这样的方法
var obj = {
'1': 'HELLO',
'2': 'BYE',
'3': 'TATA'
};
var outData = new Map();
Object.keys(obj).forEach(function (e) {
outData.set(e, obj[e])
});
要获取数据,请使用outData.get(“ key”)
现在输出数据将像-
Map(3) {"1" => "HELLO", "2" => "BYE", "3" => "TATA"}
答案 4 :(得分:0)
另一种替代方法是使用for ... in循环来迭代enums
键并构造所需的对象数组。
var enums = {
'1': 'HELLO',
'2' : 'BYE',
'3' : 'TATA'
};
let res = [];
for (key in enums)
{
res.push({number: key, word: enums[key]});
}
console.log(res);
.as-console {background-color:black !important; color:lime;}
.as-console-wrapper {max-height:100% !important; top:0;}
答案 5 :(得分:0)
您可以使用Object.keys和map
var obj = {
'1': 'HELLO',
'2' : 'BYE',
'3' : 'TATA'
};
const result = Object.keys(obj).map(el => {
return {
number: el,
word: obj[el]
}
})
console.log(result)