将对象的索引包含到数组中

时间:2019-02-13 14:47:01

标签: javascript arrays dictionary object

请有人以正确的方式指导我

我有这个对象

myObject = {"Timer13":{"Arm":0,"Mode":0},"Timer14":{"Arm":1,"Mode":1}}

我需要得到这个数组

[{"timer":"Timer13", "Arm":0,"Mode":0},{"timer":"Timer14","Arm":1,"Mode":1}]

我尝试了几种方法,但我不明白;

这是我使用地图的不完整结果

var result  = Object.keys(myObject).map((i) => myObject[i]);

我得到

 [{"Arm":0,"Mode":0},{"Arm":1,"Mode":1}]

3 个答案:

答案 0 :(得分:2)

也许尝试在从地图返回之前尝试附加键并将其余元素添加到对象中。

var myObject = {"Timer13":{"Arm":0,"Mode":0},"Timer14":{"Arm":1,"Mode":1}}

var result = Object.keys(myObject).map(elem => {
    return {timer: elem, ...myObject[elem]}
})

console.log(result)

答案 1 :(得分:1)

您可以通过分配零件来获取条目并映射新对象。

var object = { Timer13: { Arm: 0, Mode: 0 }, Timer14: { Arm: 1, Mode: 1 } },
    array = Object
        .entries(object)
        .map(([timer, values]) => Object.assign({ timer }, values));

console.log(array);
.as-console-wrapper { max-height: 100% !important; top: 0; }

答案 2 :(得分:0)

您可以使用reduce来实现当前值(curr)和 累加器(all)也会破坏数组,这对于编写更干净的代码很有帮助。 [timer,obj]计时器:curr[0],而obj是curr[1]

obj = {
  "Timer13": {
    "Arm": 0,
    "Mode": 0
  },
  "Timer14": {
    "Arm": 1,
    "Mode": 1
  }
}

const res = Object.entries(obj).reduce((all, [timer, obj]) => {
  all.push({
    timer,
    ...obj
  })
  return all;
}, [])


console.log(res)