how to extract value of two properties into an array from an array of objects?

You need to provide a specific key when destructuring an object.

Error:

const { module4.submodule } = { module4: { submodule: 4 } };

Good:

const { module4: { submodule } = { module4: { submodule: 4 } };

Same applies for creating an object, you can’t return { module4.submodule }, but you could return { module4Submodule: submodule }.

Here’s some potential solutions:

Input: Array, Output: Array

const arr = [
  {
    module: {
      module1: {
        foo: 1,
        bar: 2,
        anotherfoo: 5
      },
      module2: {
        foo: 3,
        bar: 4,
        anotherfoo: 8
      },
      module3: {
        foo: 7,
        bar: 6,
        anotherfoo: 3
      },
      module4: {
        submodule: {
          foo: 9,
          bar: 0,
          anotherfoo: 1
        }
      }
    }
  }
];

const newArr = arr.map(({ module: { module1, module4 } }) => (
  { module1, module4Submodule: module4.submodule }
));

console.log(newArr);

Input: Object, Output: Object

const obj = {
  module: {
    module1: {
      foo: 1,
      bar: 2,
      anotherfoo: 5
    },
    module2: {
      foo: 3,
      bar: 4,
      anotherfoo: 8
    },
    module3: {
      foo: 7,
      bar: 6,
      anotherfoo: 3
    },
    module4: {
      submodule: {
        foo: 9,
        bar: 0,
        anotherfoo: 1
      }
    }
  }
};

const { module: { module1, module4: { submodule } } } = obj;
const newObj = { module1, module4Submodule: submodule };

console.log(newObj);

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top