简体   繁体   English

将单个对象转换为对象数组

[英]Convert single object into array of objects

I have an object that looks like: 我有一个看起来像的对象:

var data = {first: '12/1/2019', second: '12/15/2019'}

I am trying to get into an array of objects using its keys and values like so: 我正在尝试使用其键和值进入对象数组,如下所示:

var array = [ 
  {phase: 'first', date: '12/1/2019'}, 
  {phase: 'second', date: '12/15/2019'}
]

I have tried various things, but the closest I have gotten is using something like: 我尝试了各种方法,但是最接近的方法是:

var array = Object.entries(data).map(([key, value]) => ({key,value}));

This gives me an array of objects like: 这给了我一系列对象,例如:

[ 
 {key: 'first', value: '12/1/2019'},
 {key: 'second', value: '12/15/2019'}
]

I'm close! 快到了! but i can't figure out how to change key and value to be phase and date. 但我不知道如何将键和值更改为阶段和日期。 Can someone please help me out? 有人可以帮我吗?

实际上,您可以重命名键和值参数名称:

var array = Object.entries(data).map(([phrase, date]) => ({phrase,date}));

Try adding labels in object. 尝试在对象中添加标签。

 var data = { first: '12/1/2019', second: '12/15/2019' } var array = Object.entries(data).map(([key, value]) => ({ phase: key, date: value })) console.log(array) 

You are almost there try by adding the key to return object 您几乎可以尝试添加键以返回对象

 var data = { first: '12/1/2019', second: '12/15/2019' } var array = Object.entries(data).map(([key, value]) => ({ phase: key, date: value })); console.log(array) 

You can use map() on Object.keys() 您可以在Object.keys()上使用map() Object.keys()

 var data = {first: '12/1/2019', second: '12/15/2019'} let arr = Object.keys(data).map(x => ({phase:x,date:data[x]})) console.log(arr) 

You can also use Object.entries() and map() but give different names to the parameters destructed 您也可以使用Object.entries()map()但为销毁的参数指定不同的名称

 var data = {first: '12/1/2019', second: '12/15/2019'} let arr = Object.entries(data).map(([phase,date]) =>({phase,date})) console.log(arr) 

First extract the key (phase) and value (date) from the data object by Object.entries then use Array.reduce to accumulate and form the new object into an array. 首先通过Object.entries从数据对象中提取key (阶段)和value (日期),然后使用Array.reduce累加并将新对象形成数组。

 const data = {first: '12/1/2019', second: '12/15/2019'} const arr = Object.entries(data).reduce((acc, [phase, date]) => acc.concat({phase, date}), []); console.log(arr); 

Try the following solution using for...in to iterates over all non-Symbol, enumerable properties of an object. 尝试使用for ... in以下解决方案迭代对象的所有非符号可枚举属性。

 const data = { first: '12/1/2019', second: '12/15/2019' }; const dataset = []; for (const key in data) { if (data.hasOwnProperty(key)) { const element = data[key]; dataset.push({ phase: key, date: element }); } } console.log(dataset); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM