4

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'
}
Zobla
  • 123
  • 2
  • 7

8 Answers8

2

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
);
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
1

You can use reduce to achieve your goal:

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

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

const combined = second.reduce((result, key) => {
  result[key] = new Date();
  return result;
}, { ...first });

console.log(combined);
Lajos Arpad
  • 64,414
  • 37
  • 100
  • 175
yatin
  • 11
  • 2
1

As others have pointed out, .map() produces an array, so spreading that into an object will cause the array's indexes to be added to the new object. Your approach can be modified though. Currently:

second.map(key => ({ [key]: new Date() }))

produces:

[{ "key3": <some date> }, { "key4": <some date> }]

Here, you can merge all the objects in this array into one object with the help of Object.assign(...second.map(...)):

{
  "key3": <some date>,
  "key4": <some date>
}

and then spread this object into your new object:

const combined = {
  ...first,
  ...Object.assign(...second.map(key => ({ [key]: new Date() })))
};

this can be further improved upon by passing first as an argument to Object.assign():

const combined = Object.assign({}, first, ...second.map(key => ({ [key]: new Date() })));

Above, we merge first and all the objects from the mapped second array into one object. Note that I'm passing {} as the first argument to avoid mutating the original first object:

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

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

const combined = Object.assign({}, first, ...second.map(key => ({ [key]: new Date() })));
console.log(combined);
Nick Parsons
  • 45,728
  • 6
  • 46
  • 64
0

Here is the working example:

const first = {
  key1: "some date",
  key2: "some date",
};

const second = ["key3", "key4"];

let result = second.reduce((prev, curr) => {
  return Object.assign(prev, { [curr]: new Date() });
}, first);

console.log(result);
Jerry
  • 1,005
  • 2
  • 13
0

You can use forEach and add each element in second array to result

const first = {
  key1: "some date",
  key2: "some date",
};

const second = ["key3", "key4"];

let result = { ...first};

second.forEach((element) => {
   result[element] = "some data";
});

console.log(result);
0

you can try this :

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

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

 const secondObject = {};

 second.forEach((key)=>{
   secondObject[key] = new Date();
 });

 const combined = {...first, ...secondObject} 
  • As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Aug 14 '23 at 22:15
0

You can implement a helper function that converts the array of objects into objects:

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

function getKeyValue(input) {
    let output = {};
    for (let item of input) {
        for (let key in item) {
            output[key] = item[key];
        }
    }
    return output;
}

const second = ['key3', 'key4'];
const combined = {
  ...first,
  ...getKeyValue(second.map(key => { return {[key]: new Date()}}))
}

console.log(combined);
Lajos Arpad
  • 64,414
  • 37
  • 100
  • 175
0

You can simply achieve this with a single line of code by using Array.forEach() method.

Live Demo :

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

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

second.forEach(elem => {
  if (!first[elem]) { first[elem] = 'some date' } 
})

console.log(first);
Debug Diva
  • 26,058
  • 13
  • 70
  • 123