简体   繁体   English

找到一个类似的属性然后循环对象

[英]Find a similar property then loop through object

I have two objects, car and truck. 我有两个物体,汽车和卡车。 Each car and truck will have a number property attached to it. 每辆汽车和卡车都附有一个数字属性。 However, each car can have multiple trucks related to it but only one truck number will also match the car number. 但是,每辆车可以有多辆与之相关的卡车,但只有一个卡车号码也会与车号相匹配。

Example: 例:

car
{
    number: 1054
}

truck
[{
    number: 80,
    type: "pickup",
},{
    number: 1054,
    type: "extended cab"
}, {
    number: 50,
    type: "flatbed"
}]

I would like to see if there's a way to skip having a nested loop by checking to see if they share a number property and if so, then I would like to get the properties attached to it. 我想看看是否有办法跳过嵌套循环,通过检查它们是否共享一个数字属性,如果是,那么我想得到附加的属性。

Currently I am using slightly more complicated code than below but the idea is that the user is working with one car already when they are looking for the related truck so the first loop below is simplified but the idea is the same. 目前我使用的代码比下面稍微复杂,但是想法是用户在寻找相关卡车时已经使用了一辆车,所以下面的第一个循环被简化但想法是一样的。

for (let i = 0; i < cars.length; i++) {
    car1 = cars[0].number;

    for (let j = 0; j < trucks.length; j++) {
        if (car1 === trucks[j].number) {
            console.log('Found matching truck');
        }
     }
}

I would like to know if there is a less taxing way than this or if this is what I should stick to. 我想知道是否有比这更少的税收方式,或者这是我应该坚持的方式。

I am open to using plain javascript or lodash. 我愿意使用普通的javascript或lodash。

You could use a hash table and the simply look up the number of the car. 你可以使用哈希表,只需查看汽车的数量即可。

 var trucks = [{ number: 80, type: "pickup" }, { number: 1054, type: "extended cab" }, { number: 50, type: "flatbed" }], hash = {}; trucks.forEach(function (truck) { hash[truck.number] = truck; }); console.log(hash[1054]); console.log(hash); 
 .as-console-wrapper { max-height: 100% !important; top: 0; } 

Sure you can use lodash for it 当然你可以使用lodash

https://lodash.com/docs/4.17.2# https://lodash.com/docs/4.17.2#

You can use it like that: 你可以像这样使用它:

_.forEach(cars, function(car) {
  var myTruck = _.find(trucks, function(truck) { return truck.number === car number; });
  if(myTruck === undefined)
    {
       console.log('not found');
    }
  //do what you like with it
});

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

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