如何将键值对象转换为对象数组

时间:2017-04-26 08:14:32

标签: javascript arrays typescript javascript-objects

我想将键值对象转换为javascript中的对象数组

var obj={"name1":"value1","name2":"value2",...};

如何将其转换为

arr=[{"name":"name1","value":"value1"},{"name":"name2","value":"value2"},...];

2 个答案:

答案 0 :(得分:1)

尝试使用array#mapArray#push

var obj={"name1":"value1","name2":"value2"};
var res=[];
Object.keys(obj).map(a => res.push({name:a , value:obj[a]}))
console.log(res)

答案 1 :(得分:0)

简答(ES6):

const arr = Object.entries(obj).map(([name, value]) => {
  return {
    name,
    value
  }
});

另一个答案(ES5):

var arr = Object.keys(obj).map(function(key) {
  return {
    name: key,
    value: obj[key]
  }
});