![](/img/trans.png)
[英]How to create a new array using the values of an array of objects within objects?
[英]How to create a new array of objects from an array of values in an array of objects. TypeScript?
我在下面的對象數組中有一組日期。 我希望為每個單獨的日期創建一個新的對象數組。 拆分日期並將值的 rest 復制到每個日期中。
const obj = [
{
name: 'John',
email: 'john@email.com',
dateTime: [
{
date: '26-10-1988',
start: '10:00',
end: '10:30'
},
{
date: '27-10-1988',
start: '10:00',
end: '10:30'
},
{
date: '29-10-1988',
start: '10:00',
end: '10:30'
},
]
},
{
name: 'Mary',
email: 'mary@email.com',
dateTime: [
{
date: '26-10-1988',
start: '10:00',
end: '10:30'
},
]
},
]
*編輯:
(互聯網連接不佳,不知何故在我完成之前提交了這個問題)
但這是我正在尋找的最終結果:
const newObj = [
{
name: 'John',
email: 'john@email.com',
dateTime: {
date: '26-10-1988',
start: '10:00',
end: '10:30'
}
},
{
name: 'John',
email: 'john@email.com',
dateTime: {
date: '27-10-1988',
start: '10:00',
end: '10:30'
},
},
{
name: 'John',
email: 'john@email.com',
dateTime: {
date: '29-10-1988',
start: '10:00',
end: '10:30'
},
},
{
name: 'Mary',
email: 'mary@email.com',
dateTime: {
date: '26-10-1988',
start: '10:00',
end: '10:30'
}
}
];
您可以執行以下操作:
const newArray = obj.map(i => {
return i.dateTime.map(dateObj => {
return {
name: i.name,
email: i.email,
dateTime: dateObj
};
});
});
const resultArray = [].concat.apply([], newArray);
console.log(resultArray);
resultArray
將是(數組的最后一項已展開,因此您可以檢查它):
編輯
您可以通過以下方式獲得相同的結果:
const resultArray = newArray.flat(1);
console.log(resultArray);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.