How to return key-value pairs from map function using spread operator
P粉253800312
P粉253800312 2023-08-13 17:18:34
0
1
435
<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粉253800312
P粉253800312

reply all(1)
P粉925239921

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
);
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!