首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >从嵌套对象中提取值并根据一定格式的规则(3个最小值)输出它们的键

从嵌套对象中提取值并根据一定格式的规则(3个最小值)输出它们的键
EN

Stack Overflow用户
提问于 2022-03-31 11:33:02
回答 1查看 101关注 0票数 0

我有一个带有嵌套数据的对象,需要以编程方式处理这些数据,以实现特定的输出。通过举例说明,这将是最简单的解释。

示例

我做了一个实验,测量了狗和猫奔跑的速度。我在下面的groups对象中收集了数据。我们可以看到每一组的两大类,即dogscats。然后,在每个组中,我们有一个关于组成员平均平均速度时间的属性,以及保存每个组成员数据的individuals对象。

代码语言:javascript
复制
const groups = {
  dogs: {
    groupMeanRecord: 11.7,
    individuals: {
      lassie: {
        record: 10,
        age: 2,
      },
      slinky: {
        record: 13,
        age: 4,
      },
      toto: {
        record: 11.5,
        age: 1,
      },
      marley: {
        record: 15,
        age: 1,
      },
      beethoven: {
        record: 9,
        age: 13,
      },
    },
  },
  cats: {
    groupMeanRecord: 7.75,
    individuals: {
      grumpyCat: {
        record: 6,
        age: 4,
      },
      salem: {
        record: 9,
        age: 11,
      },
      garfield: {
        record: 5,
        age: 3,
      },
      kitty: {
        record: 11,
        age: 10,
      },
    },
  },
};

我想知道在每一组动物中,谁是动物,他们的record值最低。我决定在每一组中我想要最低的三个。因此,考虑到当前的数据,我想要的输出是:

代码语言:javascript
复制
const desiredOutput = {
  dogs: 'beethoven, lassie, toto',
  cats: 'garfield, grumpyCat, salem',
};

我的尝试

下面是我能够想出的代码,它确实给出了所需的输出。但是,由于我是JavaScript新手,我认为必须有一种更简单、更直接的方法来实现这一点。

  • step 1 -清理数据以得到我所需要的

const cleanDataArrOfArrs =Object.entries(组) .map(组,groupData) => [组,=>数据)=>单株,data.record,];/“狗”,/“拉西”,10,//“斯林基”,13,//“toto”,11.5,// 'marley',15,//‘贝多芬’,9,// ],// ],/“猫”,/ 'grumpyCat',6,// 'salem',9,// 'garfield',5,// 'kitty',11,// ],/,// ]

  • step 2 -我希望使步骤1的结果成为对象

的对象。

代码语言:javascript
复制
- utilizing this helper function from [here](https://stackoverflow.com/a/63810699/6105259)

const makeObject = (arr) => {返回Object.fromEntries( arr.map(key,val) => Array.isArray(val)?密钥,makeObject( val ):key,val );};

代码语言:javascript
复制
- calling `makeObject()` on `cleanDataArrOfArrs`

const cleanDataObj = makeObject(cleanDataArrOfArrs) /狗:{ lassie: 10,slinky: 13,toto: 11.5,marley: 15,贝多芬:9 },//猫:{ grumpyCat: 6,salem: 9,garfield: 5,kitty: 11 },// };

  • step 3 -现在我想从最低到最大的cleanDataObj.dogscleanDataObj.cats属性排序

代码语言:javascript
复制
- utilizing a helper function from this [answer](https://stackoverflow.com/a/37607084/6105259):

const sortObj = (o) => Object.fromEntries(Object.entries(o).sort((a,b) => a1 - b1));

代码语言:javascript
复制
- and finally:

const myOutput = Object.fromEntries( Object.entries(cleanDataObj).map((k,v) => k,Object.keys(sortObj(v)).slice(0,3).join(',‘,') );// { //狗:’贝多芬,拉西,toto',//猫:'garfield,grumpyCat,salem',/ };

我担心的是,这段代码虽然工作正常,但既不可读性,也不能正确地处理任务,而且可能有一种更简单的方法来处理这个问题。因此,我很乐意了解这样一项任务是如何完成的。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-04-03 12:04:27

这可能是实现预期目标的一种可能的解决办法。

代码片段

代码语言:javascript
复制
// helper method
const getIndNames = obj => (
  Object.entries(obj)                   // iterate over key-value pairs
  .map(([k, v]) => ({name: k, ...v}))   // get an array of objects with 'name', 'record', 'age' props
  .sort((a, b) => a.record - b.record)  // sort the array descending order of record
  .filter((_, idx) => (idx < 3))        // filter to retain top 3
  .map(({name}) => name)                // extract just the 'name' prop
  .join(', ')                           // use '.join' to generate a comma-separated string
);

// method that iterates over each group (cats, dogs)
const fastestThree = obj => (
  Object.fromEntries(                     // convert the final-result back into object
    Object.keys(obj).map(                 // iterate over key-value pairs of 'obj'
      k => ([                             // for each key, return an array of 2 elements
        [k],                              // first is the key 'k' itself
        getIndNames(obj[k].individuals)   // second is the fastest-three cats/dogs
      ])
    )
  )
);

// data from the question
const groups = {
  dogs: {
    groupMeanRecord: 11.7,
    individuals: {
      lassie: {
        record: 10,
        age: 2,
      },
      slinky: {
        record: 13,
        age: 4,
      },
      toto: {
        record: 11.5,
        age: 1,
      },
      marley: {
        record: 15,
        age: 1,
      },
      beethoven: {
        record: 9,
        age: 13,
      },
    }
  },
  cats: {
    groupMeanRecord: 7.75,
    individuals: {
      grumpyCat: {
        record: 6,
        age: 4,
      },
      salem: {
        record: 9,
        age: 11,
      },
      garfield: {
        record: 5,
        age: 3,
      },
      kitty: {
        record: 11,
        age: 10,
      },
    },
  }
};

// invoke the method and print the result
console.log(fastestThree(groups));
代码语言:javascript
复制
.as-console-wrapper { max-height: 100% !important; top: 0; }

解释

上述代码片段中的内联注释解释了解决方案的重要方面。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/71691737

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档