0

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

1
  • 1
    Nothing in your question has anything to do with JSON. The result you try to achieve is just a regular JavaScript array (containing regular JavaScript objects). Commented Sep 8, 2022 at 9:59

1 Answer 1

2

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)

Sign up to request clarification or add additional context in comments.

1 Comment

thanks I'm new to this and haven't use "reduce()" before. For sure I'm gonna check it out

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.