Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return key value pairs from map function using spread operator

I have an object and an array. Say:

const first = { 
  'key1': 'some date',
  'key2': 'some date'
}

const second = ['key3', 'key4']

Then using spread syntax I want to combine then into single object. For each item in array I want to create new key value pair and put it inside this combined object. For now I am only able to return object from map function instead of key value pairs. How to change this?

const combined = {
  ...first,
  ...second.map(key => ({ [key]: new Date() })) // return key value instead of object
}

What I get:

{
  '0': { key3: 'some date' },
  '1': { key4: 'some date' },
  key1: 'some date',
  key2: 'some date'
}

What I want:

{
  key1: 'some date',
  key2: 'some date',
  key3: 'some date',
  key4: 'some date'
}
like image 261
Zobla Avatar asked Sep 01 '25 01:09

Zobla


1 Answers

You can’t. map outputs an array (which each value is the result of passing the value at the matching index from the original array through a function). If you spread an array into an object you get the indexes (numbers) as property names and the values as values.

If you want to start with an array and end up with an object then map is the wrong tool. Use reduce instead.

Something along the lines of:

const combined = second.reduce(
    (prev, curr) => {
        return {
            ...prev,
            [curr]: new Date()
        };
    },
    first
);
like image 149
Quentin Avatar answered Sep 02 '25 15:09

Quentin