简体   繁体   English

打字稿从对象创建数组

[英]Typescript create array from object

How can I convert the following object:如何转换以下对象:

{
  Value1: 1,
  Value2: 3
}

into an array that looks like this:变成一个如下所示的数组:

[
 {name: Value1, position: 1},
 {name: Value2, position: 3}
]

I've tried using Object.keys , but didn't really get the desired results.我试过使用Object.keys ,但并没有真正得到想要的结果。

You can get the array of [key, value] pairs using Object.entries function.您可以使用Object.entries函数获取[key, value]对的数组。

 const input = { Value1: 1, Value2: 3 }; const output = Object.entries(input).map((item) => ({ name: item[0], position: item[1] })); console.log(output);


function convertToArray(obj){
   return  Object.keys(obj).map(prop => {
      return {
           name: prop, 
           position: obj[prop]
      };
});

console.log(convertToArray({ Value1: 2}));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM