简体   繁体   English

如何从对象数组中提取两个属性的值到数组中

[英]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.嗨,有一个具有 4 个属性的对象数组,我只需要从中提取 2 个。

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.如何使用 map 将 module1 和 module4.submodule 提取到新数组中。

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 } .同样适用于创建对象,您不能返回{ module4.submodule } ,但您可以返回{ 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您可以为对象实现一个getDotPath

 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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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