将平面对象转换为单个 属性 个对象的数组

Transform flat object into array of single property objects

ES6+ 中最简洁的转换方式是什么:

{
  'key 1': 'value 1',
  'key 2': 'value 2',
  'key 3': 'value 3'
}

进入这个:

[
  { 'key 1': 'value 1' },
  { 'key 2': 'value 2' },
  { 'key 3': 'value 3' }
]

我建议使用 Object.entries(), then Array.Map(), along with some destructuring 将单个对象转换为键/值对数组:

const obj = {
  'key 1': 'value 1',
  'key 2': 'value 2',
  'key 3': 'value 3'
}

const arr = Object.entries(obj).map(([key, value]) => ({ [key]: value }));
console.log('Result:', arr)
.as-console-wrapper { max-height: 100% !important; top: 0; }

另一种方法是简单地使用 Object.keys(),然后使用 obj[key]:

访问每个值

const obj = {
  'key 1': 'value 1',
  'key 2': 'value 2',
  'key 3': 'value 3'
}

const arr = Object.keys(obj).map(key => ({ [key]: obj[key] }));
console.log('Result:', arr)
.as-console-wrapper { max-height: 100% !important; top: 0; }