简体   繁体   中英

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

Hi have an array of object with 4 properties, i need to extract only 2 from them.

sample array of object

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
       }
      }
      }];

How can I use map to extract module1 and module4.submodule into a new array.

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);

You could implement a getDotPath for object

 const getDotPath = (dotPath, obj) => { try { return dotPath.split(".").reduce((acc, prop) => acc[prop], obj) } catch (err) { return undefined } } 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 dotPaths = ["module1", "module4.submodule"] const res = arr.map((el) => dotPaths.map((dotPath) => getDotPath(dotPath, el.module)) ) console.log(res)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM