陷入与具有 ID 的对象的比较数组

问题描述 投票:0回答:2

我有 2 个带有对象的数组

  1. 与汽车品牌
const brands = [
   { id: 1, name: "Mercedes Benz", bodyType: [1, 3] },
   { id: 2, name: "Audi", bodyType: [1, 2] },
   { id: 3, name: "BMW", bodyType: [3, 4] },
   { id: 4, name: "Mazda", bodyType: [1, 2, 4] }
];
  1. 与体型
const bodyTypes = [
   { id: 1, type: "Sedan"},
   { id: 2, type: "Coupe"},
   { id: 3, type: "Hatchback"},
   { id: 4, type: "SUV"}
];
  1. 我已经选好类型了
const pickedTypes = [2, 4] // Coupe & SUV

如何比较这两个数组以获得具有 pickTypes 中体型的品牌的新数组

我尝试获取我想要的数组

const brands = [
   { id: 1, name: "Mercedes Benz", bodyType: [1, 3] },
   { id: 2, name: "Audi", bodyType: [1, 2] },
   { id: 3, name: "BMW", bodyType: [3, 4] },
   { id: 3, name: "Mazda", bodyType: [1, 2, 4] }
];

const bodyTypes = [
   { id: 1, type: "Sedan"},
   { id: 2, type: "Coupe"},
   { id: 3, type: "Hatchback"},
   { id: 4, type: "SUV"}
];

const pickedTypes = [2, 4] // coupe & suv

let newBrandsByPickedTypes = [];

// loop for every type
for(let i = 0; i < pickedTypes.length; i++){
  // loop for every brand
  for(let k = 0; k < brands.length; k++){
      // loop for every type in brand
      brands[k].bodyType.forEach((type) => {
        // if brand has type that in pickedTypes push this brand to newBrandsByPickedTypes 
        if(type === pickedTypes[i]){
            newBrandsByPickedTypes.push(brands[k])
        }
      })
  }

}

newBrandsByPickedTypes && console.log(newBrandsByPickedTypes); // output audi, mazda, bmw

我实际上陷入了这么多循环..

看起来可行,但我有类似警告的内容:[圆形对象对象]]

javascript arrays filter comparison
2个回答
0
投票

您可以根据 PickTypes 中的任何 id 是否存在于各个品牌的 bodyType 数组中来从 Brands 数组中进行过滤。这是一个可能的解决方案

brands.filter(brand => pickedTypes.some(type => brand.bodyType.includes(type))).map(brand => brand.name)

输出

['Audi', 'BMW', 'Mazda']

在这种情况下,由于pickedType已经包含id而不是名称,因此不需要bodyTypes数组,如果pickedTypes有“Sedan”,“Coupe”等,您可以从bodyTypes映射id并使用该数组进行搜索


0
投票

我可以看到您正在尝试比较两个数组以获得一个新数组,其中品牌的体型位于pickedTypes数组中。您的代码有效,但您收到有关圆形对象的警告消息。

此警告通常意味着您的代码正在对象之间创建循环引用,从而导致无限循环。我建议检查您的对象以查看其中是否存在循环引用。

此外,您还可以使用filter()方法过滤掉pickedTypes数组中没有body类型的品牌,从而简化代码。这是一个例子:

brands.filter(brand => pickedTypes.some(type => brand.bodyType.includes(type))).map(brand => brand.name)

此代码使用filter()方法过滤掉pickedTypes数组中没有任何体型的品牌。 some()方法用于检查品牌中的任何身体类型是否在pickedTypes数组中。

我希望这有帮助!

© www.soinside.com 2019 - 2024. All rights reserved.