将对象映射到ES6中的对象数组 [英] Mapping an object to array of objects in ES6

查看:253
本文介绍了将对象映射到ES6中的对象数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将对象转换为对象数组,同时保留键名?

  // actual 
obj = {
key1:null,
key2:Nelly,
key3:[suit,汗]
}

/ / expected
arr = [
{key2:Nelly},
{key3:[suit,汗]}
]

目前我的解决方案是...

  var arr = Object.keys(obj).map(key => {if(obj [key])return {key:obj [key]}}) 

其中返回

 code> arr = [
undefined,
{key:Nelly},
{key:[suit,汗]}
]


解决方案

.map()返回与原始数组相同长度的数组。在某些情况下,回调代码不返回值的代码将导致值 undefined 的元素。处理这种情况的一种方法是先将 .filter()出您不想保留的元素。



无论如何,要获取所需的密钥名称,您可以使用一个对象文字与计算属性名称

  {[key]:obj [key]} 

在上下文中:



  const obj = {key1:null,key2:'Nelly',key3:['suit','sweat']} const arr = Object.keys ).filter(v => obj [v]!= null).map(key =>({[key]:obj [key]}))console.log(arr) / pre> 


How would I convert a object to an array of objects while keeping key names?

// actual 
obj = {
  key1: null,
  key2: "Nelly",
  key3: [ "suit", "sweat" ]
} 

// expected 
arr = [
  { key2: "Nelly" },
  { key3: [ "suit", "sweat" ] }
]

currently my solution is...

 var arr = Object.keys(obj).map(key => { if (obj[key]) return { key: obj[key] } });

which returns

arr = [
  undefined,
  { key: "Nelly" },
  { key: [ "suit", "sweat" ] }
]

解决方案

.map() returns an array of the same length as the original array. Code like yours with a callback that doesn't return a value in some cases will result in elements with the value undefined. One way to deal with that is to first .filter() out the elements you don't want to keep.

Anyway, to get the key names you want you can use an object literal with a computed property name:

{ [key]: obj[key] }

In context:

const obj = {
  key1: null,
  key2: 'Nelly',
  key3: [ 'suit', 'sweat' ]
}

const arr = Object.keys(obj)
  .filter(v => obj[v] != null)
  .map(key => ({ [key]: obj[key] }))

console.log(arr)

这篇关于将对象映射到ES6中的对象数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆