Home  >  Q&A  >  body text

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

<p>I have an object and an array. Assumption:</p> <pre class="brush:php;toolbar:false;">const first = { 'key1': 'some date', 'key2': 'some date' } const second = ['key3', 'key4']</pre> <p>Then use extended syntax to merge them into a single object. For each item in the array, I want to create a new key-value pair and put it into this merged object. Currently, I can only return objects from the map function, not key-value pairs. How to change this? </p> <pre class="brush:php;toolbar:false;">const combined = { ...first, ...second.map(key => ({ [key]: new Date() })) // Return key-value pairs instead of objects }</pre> <p>The result I got:</p> <pre class="brush:php;toolbar:false;">{ '0': { key3: 'some date' }, '1': { key4: 'some date' }, key1: 'some date', key2: 'some date' }</pre> <p>The result I want:</p> <pre class="brush:php;toolbar:false;">{ key1: 'some date', key2: 'some date', key3: 'some date', key4: 'some date' }</pre> <p><br /></p>
P粉253800312P粉253800312433 days ago448

reply all(1)I'll reply

  • P粉925239921

    P粉9252399212023-08-14 14:46:08

    Cannot do this. map Outputs an array (where each value is the result of passing the value at the matching index in the original array to the function). If you expand the array into an object, you will get the index (number) as the property name and the value as the value.

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

    Code similar to the following:

    const combined = second.reduce(
        (prev, curr) => {
            return {
                ...prev,
                [curr]: new Date()
            };
        },
        first
    );
    

    reply
    0
  • Cancelreply