比较2个对象数组(带参数)并返回equals

时间:2017-12-29 13:51:56

标签: javascript arrays react-native

我有这2个数组:

var a = [{cod: 123, brand: 'Audi', model: 'A3', price: 15000, km: 20000}, 
         {cod: 456, brand: 'BMW', model: 320, price: 20000, km: 30000}]
var b = [{brand: 'Audi', model: 'A3', price: 100000, km: 100000}]

我想要做的是,比较两个数组,并将a中的对象作为与b相同的品牌和型号返回,并且仅当最高价格和km不超过100000时。 如果a上的奥迪价格为120000,则不会返回任何东西。

编辑: Nina的答案非常完美。但如果过滤器上的某个项目为空,则不会返回任何内容。我如何忽略空值并仅比较其他值?

3 个答案:

答案 0 :(得分:2)

您可以使用过滤器值过滤数组。



var array = [{ cod: 123, brand: 'Audi', model: 'A3', price: 15000, km: 20000 }, { cod: 456, brand: 'BMW', model: '320', price: 20000, km: 30000 }],
    filter = [{ brand: 'Audi', model: 'A3', price: 100000, km: 100000 }],
    result = array.filter(a => filter.some(b => a.brand === b.brand && a.model === b.model && a.price <= b.price && a.km <= b.km));

console.log(result);
&#13;
&#13;
&#13;

答案 1 :(得分:0)

像这样

&#13;
&#13;
const a = [
    {
        cod: 123,
        brand: 'Audi',
        model: 'A3',
        price: 15000,
        km: 20000,
    },
    {
        cod: 456,
        brand: 'BMW',
        model: 320,
        price: 20000,
        km: 30000,
    },
];

const b = [
    {
        brand: 'Audi',
        model: 'A3',
        price: 100000,
        km: 100000,
    },
];
function compareTwo(a, b) {
    let obj = {};
    for (let element of a) {
        if (element.model === b[0].model && element.brand === b[0].brand) {
            if (b[0].price <= 100000 && 100000 >= b[0].km)
                obj.model = element.model;
                obj.brand = element.brand;
                if(element.price === 100000) return null ;
               return obj ;
        }
    }
    return null ;
}
let myObj = compareTwo(a,b);
console.log(myObj);
&#13;
&#13;
&#13;

答案 2 :(得分:0)

Nina和我的答案相同,所以这里有一个扩展版本允许使用动态键进行搜索,如果它是一个数字,则汽车参数需要小于或等于搜索参数。< / p>

&#13;
&#13;
const cars = [
  {cod: '123', brand: 'Audi', model: 'A3', price: 15000, km: 20000},  // pass
  {cod: '123', brand: 'Audi', model: 'A3', price: 30000, km: 40000},  // pass 
  {cod: '124', brand: 'Audi', model: 'A6', price: 15000, km: 120000}, // pass 2nd query
  {cod: '125', brand: 'Audi', model: 'A8', price: 150000, km: 12000}, // fail price
  {cod: '456', brand: 'BMW', model: '320', price: 20000, km: 30000},  // fail all
]

const searches = [
  {brand: 'Audi', model: 'A3', price: 100000, km: 100000},
  {brand: 'Audi', model: 'A6'}
]

console.log(
  // filter the cars
  cars.filter(car =>
    // iterate over the searches array to check the car to the search params
    searches.some(
      // check the requirements
      search => (
        // loop over each key in the search params object
        Object.keys(search).every(
          key => isNaN(search[key])
            ? car[key] === search[key]
            : car[key] <= search[key]
        )
      )
    )
  )
)
&#13;
<script src="https://codepen.io/synthet1c/pen/KyQQmL.js"></script>
&#13;
&#13;
&#13;