Remove object key but keep its properties

Viewed 23

Let's say there is an object that looks like this:

const before = {
  keyToBeRemoved: {    // <-- remove the key
    name1: "value 1",  // <-- keep the property
    name2: "value 2",  // <-- keep the property
    name3: "value 3",  // <-- keep the property
  },
  name4: "value 4",
  name5: "value 5",
  name6: "value 6",
};

I would like to remove the top level key but also want to keep all of its properties. The final result should look like this:

const after = {
  name1: "value 1",
  name2: "value 2",
  name3: "value 3",
  name4: "value 4",
  name5: "value 5",
  name6: "value 6",
};

Could you advise what is pattern to perform such manipulations with objects?

1 Answers

One (of many) possible solution is to use the spread syntax.

First destruct the original object by "dividing" the object in the key to be removed and all the other properties. Then construct a new object using all the other properties and the properties of the key that was removed.

const before = {
  keyToBeRemoved: {    // <-- remove the key
    name1: "value 1",  // <-- keep the property
    name2: "value 2",  // <-- keep the property
    name3: "value 3",  // <-- keep the property
  },
  name4: "value 4",
  name5: "value 5",
  name6: "value 6",
};
const { keyToBeRemoved, ...withoutKeyToBeRemoved  } = before; 
const after = { ...keyToBeRemoved, ...withoutKeyToBeRemoved }
console.log(after)
.as-console-wrapper { max-height: 100% !important; top: 0; }

Related