Home > OS >  (JS) creating a JSON with 2 arrays when the element of one array is the the key for the others
(JS) creating a JSON with 2 arrays when the element of one array is the the key for the others

Time:09-09

so I have these 2 arrays

  let answers = ['good', ' bad', 'ehh']
  let question = [
    'how are you',
    'how the weather',
    'how was the day',
    'what do you think about',
  ]

and I want to archive this result

  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 },
  ]

so I want the element of answer array to be the keys of the final array, I tried some mapping methods but didn't achieve what I wanted.

Any solution is highly appreciated

CodePudding user response:

map() with a nested reduce() to create the objects with FALSE value:

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)

  • Related