Home > Enterprise >  Create an object based on another object
Create an object based on another object

Time:01-29

I have an object that looks like this:

let Object1 = { id1: { date: '23-01-2023', status: 'completed' }, id2: { date: '02-01-2023', status: 'pending' } }

How can I make a new object that has only every key of the object, but also the value of one of the keys on the nested object, like this:

let Object2 = { id1: 'completed', id2: 'pending' }

CodePudding user response:

You can map over Object.entries, replacing each value with the status property of that nested object, then create a new object with Object.fromEntries.

let obj1 = { id1: { date: '23-01-2023', status: 'completed' }, id2: { date: '02-01-2023', status: 'pending' } }
let res = Object.fromEntries(Object.entries(obj1).map(([k, v]) => [k, v.status]));
console.log(res);

CodePudding user response:

You can use the Object.keys() method to get an array of the keys of the original object, and then use the Array.prototype.reduce() method to create a new object with the desired properties.

let Object1 = { id1: { date: '23-01-2023', status: 'completed' }, id2: { date: '02-01-2023', status: 'pending' } }

let Object2 = Object.keys(Object1).reduce((acc, key) => {
    acc[key] = Object1[key].status;
    return acc;
}, {});
console.log(Object2)

This will create a new object (Object2) that has the same keys as the original object (Object1), but the values are the status property of the nested object.

Alternatively, You can also use Object.entries() function that returns an array of the object's own enumerable string-keyed property [key, value] pairs, in the same order as that provided by a for...in loop.

let Object1 = { id1: { date: '23-01-2023', status: 'completed' }, id2: { date: '02-01-2023', status: 'pending' } }

let Object2 = Object.fromEntries(Object.entries(Object1).map(([key, value]) => [key, value.status]));
console.log(Object2)

CodePudding user response:

Get the keys of object1 and use the reduce function to populate the new object.

const object2 = Object.keys(object1).reduce((res, key) => {
  res[key] = object1[key].status;
  return res;
}, {});
  • Related