首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >循环自动排样

循环自动排样
EN

Stack Overflow用户
提问于 2022-04-11 13:08:10
回答 1查看 49关注 0票数 -1

我有一个包含对象的数组,这些对象由一些数组组成。我想循环遍历整个数组和对象内部的数组。听起来很复杂,但是如果你看下面的例子,它是有效的。然而,我的问题是,现在变量数组的长度是2,但是如果数组长度为4而不硬编码,那么如何实现循环中的这种循环类型,因为我将从变量上变化很大的api中获得数据。

代码语言:javascript
复制
let wantedArray =[]
let array = [
  { gender: male, value: 10, age: 5,countryofbirth:"Norway" },
  { gender: female, value: 10, age: 2,countryofbirth:"Sweden" },
{ gender: male, value: 15, age: 3,countryofbirth:"Norway" },
{ gender: male, value: 11, age: 4,countryofbirth:"Norway" },
{ gender: female, value: 10, age: 2,countryofbirth:"Finland" },
  ...
]
let variables = [
  { id: gender, options: [male, female] },
  { id: "countryofbirth",  options: ["Norway", "Sweden", "Denmark", "Finland"]}
]
variables[0].options.map((item) => {
  variables[1].options.map((item2) => {
    let currArray = array.filter((currData) =>
      currData[variables[0].id] === item &&
      currData[variables[1].id] === item2);

//lets say that it have come to the point in the loop where item===male and item2==="Norway"

    let currObject ={variables[0].id:item//"Male",
variables[1].id:item2}//"Norway"
let currValues ={}
    currArray.map((data)=>{
    currValues[data.age]=value
})
currObject["values"]=currValues
wantedArray.push(currObject)
/*This means when item===male and item2==="Norway" the function would push {
gender:"Male",
countryofbirth:"Norway,
values:{5:10,3:15,4:11}
} to wantedArray*/
  })
})
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-04-11 14:18:18

我想你可能是在找

代码语言:javascript
复制
const data = [
  {gender: "male", value: 10, age: 5, countryofbirth: 'Norway'},
  {gender: "female", value: 10, age: 2, countryofbirth: 'Sweden'},
  {gender: "male", value: 15, age: 3, countryofbirth: 'Norway'},
  {gender: "male", value: 11, age: 4, countryofbirth: 'Norway'},
  {gender: "female", value: 10, age: 2, countryofbirth: 'Finland'},
]

// These are all dynamic.
const filter = {gender: "male", countryofbirth: 'Norway'};
const valueKey = 'age';
const valueValue = 'value';

// Find objects with key/values matching all of those in `filter`.
const matching = data.filter((item) => Object.entries(filter).every(([key, value]) => item[key] === value));
console.log(matching);

// Generate a mapping from the found objects using the `valueKey` and `valueValue` variables.
const values = Object.fromEntries(matching.map((item) => [item[valueKey], item[valueValue]]));

// Merge the filter and the values to get the desired result.
console.log({...filter, values});

终于打印出来了

代码语言:javascript
复制
{
  gender: 'male',
  countryofbirth: 'Norway',
  values: { '3': 15, '4': 11, '5': 10 }
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/71828424

复制
相关文章

相似问题

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