所以我有這兩個陣列
let answers = ['good', ' bad', 'ehh']
let question = [
'how are you',
'how the weather',
'how was the day',
'what do you think about',
]
我想存檔這個結果
let final = [
{ title: 'how are you', good: false, bad: false, ehh: false },
{ title: 'how the weather', good: false, bad: false, ehh: false },
{ title: 'how was the day', good: false, bad: false, ehh: false },
{ title: 'what do you think about', good: false, bad: false, ehh: false },
]
所以我希望答案陣列的元素成為最終陣列的鍵,我嘗試了一些映射方法但沒有達到我想要的。
任何解決方案都受到高度贊賞
uj5u.com熱心網友回復:
map()使用嵌套reduce()創建具有FALSE值的物件:
const answers = [ 'good', 'bad', 'ehh' ];
const question = [
'how are you',
'how the weather',
'how was the day',
'what do you think about'
];
const res = question.map(title => ({
title,
...answers.reduce((p, c) => (p[c] = false, p), {})
}));
console.log(res)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/505604.html
標籤:javascript 数组 json
