简体   繁体   中英

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()

 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

 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.

 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.

 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); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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