0

This is my array:

const arr = ['first string', 'second string'];

How can I map this, so I get:

const obj = {'first string': 'found', 'second string', 'found'};

I have tried this:

const obj = arr.forEach(item => {item: 'found'}) but it is not working.

storagemode11
  • 875
  • 7
  • 11

4 Answers4

3

You can use Array.reduce() instead of forEach()

BUT, you cannot assign duplicate keys to an object.

const arr = ['some string', 'some string', 'another string', 'totally different'];


var obj = arr.reduce((acc, cur) => {
  acc[cur] = 'found'
  return acc;
}, {});

console.log(obj);
Harun Yilmaz
  • 8,281
  • 3
  • 24
  • 35
1

Try this:

const arr = ['first string', 'second string'];
const res = Object.assign({}, ...arr.map((s) => ({[s]: 'found'})));

console.log(res);
Sebastian Kaczmarek
  • 8,120
  • 4
  • 20
  • 38
1

You can do something like this:-

const obj = {};
arr.forEach(item => {
    obj[item] = 'found';
});
Shivratna Kumar
  • 1,311
  • 1
  • 8
  • 18
1

Not so sure about what you want, but this maybe your solution:

const arr = ['some string1', 'some string2'];
const ans = Object.fromEntries(arr.map(item => [item, 'found']));
console.log(ans);
Sebastian Kaczmarek
  • 8,120
  • 4
  • 20
  • 38
Wan Chap
  • 841
  • 7
  • 13