如何将这个基于ID的对象转换为对象数组?

时间:2018-03-22 09:37:25

标签: javascript arrays

我有这样的数据:

{
  "-L8BpxbS70KYrZMQUF0W": {
    "createdAt": "2018-03-22T16:33:57+08:00",
    "email": "ss@ss.ss",
    "name": "ss"
  },
  "-KYrZMQUF0WL8BpxbS70": {
     // etc.
   }
}

我想谈谈这个:

[{
  id: '-L8BpxbS70KYrZMQUF0W
  createdAt: "2018-03-22T16:33:57+08:00",
  email: "ss@ss.ss",
  name: "ss"
}, {
  id: -KYrZMQUF0WL8BpxbS70"
  // etc.
}]

我从这开始:

  Object.keys(idBasedObjects).forEach(key => {
    console.log(resp[key])
  })

但我得undefined

创建此阵列的最佳方法是什么?

2 个答案:

答案 0 :(得分:7)

使用Object.entries()获取密钥和值,并使用Array.map()object spread获取到所需的表单:



const obj = {"-L8BpxbS70KYrZMQUF0W":{"createdAt":"2018-03-22T16:33:57+08:00","email":"ss@ss.ss","name":"ss"},"-KYrZMQUF0WL8BpxbS70":{}};

const result = Object.entries(obj).map(([id, props]) => ({
  id,
  ...props
}));

console.log(result);




答案 1 :(得分:2)

使用<DataTemplate> <ContentControl> <ContentControl.Style> <Style TargetType="ContentControl"> <Style.Triggers> <DataTrigger Binding="{Binding ColumnName}" Value="Name1"> <Setter Property="Template" Value="{StaticResource Template1}" /> </DataTrigger> <DataTrigger Binding="{Binding ColumnName}" Value="Name2"> <Setter Property="Template" Value="{StaticResource Template2}" /> </DataTrigger> ... </Style.Triggers> </Style> </ContentControl.Style> </ContentControl> </DataTemplate> Object.keysObject.assign

map

<强>演示

&#13;
&#13;
var output = Object.keys(obj).map( s => Object.assign( obj[s], {id : s} ))
&#13;
&#13;
&#13;