[英]Best way to map and objects in an array to single object
我正在尝试将基于类型的答案属性映射到一个新的单个对象
const questionsArray = [
{
question: `What is your name?`,
type: "name"
},
{
question: `What is your age?`,
type: "age"
}
]
这将导致:
bday = {
name: 'Jose',
age: '23',
}
这是行不通的,因为每个问题都会替换之前已经设置的值,因为类型会有所不同
您可以使用reduce()
并使用type
作为键并将answer
作为该键的值
const questionsArray = [ { id: 0, question: `What is your name?`, answer: 'jose', type: "name" }, { id: 1, question: `What is your birth month?`, answer: 'January', type: "month" }, { id: 2, question: `What day in were you born?`, answer: '24', type: "day" }, { id: 3, question: `What's your email?`, answer: 'k@k.gmail.com', type: 'email' }] const res = questionsArray.reduce((ac, {type, answer}) => { ac[type] = answer; return ac; }, {}); console.log(res)
正如您将在上述方式中注意到的,除了数组值的type
属性之外,您不能使用任何其他键。
如果要在结果对象中包含自定义属性名称,则需要有一个哈希表。
const questionsArray = [ { id: 0, question: `What is your name?`, answer: 'jose', type: "name" }, { id: 1, question: `What is your birth month?`, answer: 'January', type: "month" }, { id: 2, question: `What day in were you born?`, answer: '24', type: "day" }, { id: 3, question: `What's your email?`, answer: 'k@k.gmail.com', type: 'email' }] const table = { day: 'birthDay', month: 'birthMonth' } const res = questionsArray.reduce((ac, {type, answer}) => { ac[table[type] || type] = answer; return ac; }, {}); console.log(res)
您可以使用.map()
将每个对象映射到一个以type
为键、以answer
为值的新对象。 然后,您可以使用Object.assing()
从这个映射对象数组构建一个更大的结果对象:
const questionsArray = [ { id: 0, question: `What is your name?`, answer: 'jose', type: "name" }, { id: 1, question: `What is your birth month?`, answer: 'January', type: "month" }, { id: 2, question: `What day in were you born?`, answer: '24', type: "day" }, { id: 3, question: `What's your email?`, answer: 'k@k.gmail.com', type: 'email' } ]; const bday = Object.assign(...questionsArray.map(({answer, type}) => ({[type]: answer}))); console.log(bday);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.