问题:
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:...
可以将文章内容翻译成中文,广告屏蔽插件会导致该功能失效:
问题:
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?
回答1:
You can actually just rename your key and value parameter names:
var array = Object.entries(data).map(([phrase, date]) => ({phrase,date}));
回答2:
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)
回答3:
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)
回答4:
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);
回答5:
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)
回答6:
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);