在 JavaScript 中将数组与对象数组进行比较

Comparing an Array with an Objects' Array in JavaScript

本文关键字:数组 比较 对象 JavaScript      更新时间:2023-09-26

我是JavaScript的新手,想知道如何将一个数组与另一个由JavaScript对象组成的数组进行比较。

  1. 该数组是一系列采用"YYYY-MM-DD"格式的排序时间。
  2. 对象数组错过了几天的一些价格值。
  3. 我想找到丢失的值并将其分配为"NULL"。

例如,我有一个数组:

array = ['2014-10-09','2014-10-10','2014-10-11','2014-10-12'];

以及一个数组,其对象为:

objArray = [{
    date:"2014-10-09",
    price:"100"
},
{
    date:"2014-10-10",
    price:"99"
},
{
    date:"2014-10-12",
    price:"102"
}];

我想以这种方式获取价格数组:

priceResult = [100, 99, "NULL", 102];

不使用其他库的最有效方法是什么?我想看看是否有人有更优雅的解决方案。我非常感谢您的帮助。

您可以从对象数组创建一个查找集,然后可以使用它来将日期转换为价格。

这扩展得很好,因为它是一个 O(n+m( 解决方案,而不是如果你在循环中使用循环来查找价格时得到的 O(n*m( 解决方案。

var array = ['2014-10-09','2014-10-10','2014-10-11','2014-10-12'];
var objArray = [{ date:"2014-10-09", model:"A", price:"100" },{ date:"2014-10-10", model:"A", price:"99" },{ date:"2014-10-12", model:"A", price:"102" }];
var lookup = {};
for (var i = 0; i < objArray.length; i++) {
  lookup[objArray[i].date] = parseInt(objArray[i].price, 10);
}
var priceResult = [];
for (var i = 0; i < array.length; i++) {
  if (lookup.hasOwnProperty(array[i])) {
    priceResult.push(lookup[array[i]]);
  } else {
    priceResult.push('NULL');
  }
}
// output result in StackOverflow snippet
document.write(JSON.stringify(priceResult));

注意:您可能希望改用值null而不是字符串'NULL',因为它通常更容易处理。

lodash 是最好的库。但是您确实说了"不使用其他库",因此您需要在本地执行此操作。

最简单的方法是嵌套循环:

var i, j, d, res = [];
for (i=0; i<dateArray.length; i++) {
  d = dateArray[i];
  for (j=0; j<objArray.length; j++) {
    if (objArray[j] && objArray[j].date && objArray[j].date === d) {
       res.push(objArray[j].price);
       j = objArray.length; // don't waste energy searching any more, since we found it
    }
  }
}
// res now contains all you wanted

如果 objArray 真的很大,并且您不想多次搜索它,那么您可以将其转换为按日期索引的对象:

var i, obj = {}, d, res = [];
for (i=0; i<objArray.length; i++) {
  if (objArray[i] && objArray[i].date) {
    obj[objArray[i].date] = objArray[i];
  }
}
for (i=0; i<dateArray.length; i++) {
  d = dateArray[i];
  res.push(obj[d] ? obj[d].price : null : null);
}
// res now contains all you wanted

遍历对象并在数组中搜索日期

// Add contains to array proto: http://css-tricks.com/snippets/javascript/javascript-array-contains/
var priceResult = [];
for(var i in objArray) {
    if(dateArray.contains(objArray[i].date)) priceResult.push(objArray[i].date));
}
console.log('matches:', priceResult);

此函数将为您提供对象数组中所有单个数组的映射

function getArrayMap(array) {
    var map={}
    for(var i=0;i<array.length;i++){
        var o = array[i];
        for(var k in o){
            if(!map[k]){
                map[k]=[];
            }
            map[k].push(o[k]);
        }
    }
    return map;
}

你可以像这样使用它——

var map = getArrayMap(objArray);
console.log(map["date"]);//date array
console.log(map["price"]);//price array
console.log(map["model"]);//model array

如果我正确理解了您的问题,对于数组中的所有值,您要检查 objArr 并找到每个日期的价格,如果没有找到,则要插入 null。如果这是您想要的,那么以下内容会有所帮助

       var found= false; 
       var list=[];  
    for(var i=0; i< dateArray.length; i++)
    {
        for(var j=0; j< objArray.length; j++)
        {
            if(objArray[j].date ==  dateArray[i])
            {
            list.push(objArray[j].price);
            found =  true;
            }
        }
        if(!found)
        {
        list.push("null");
        }
        found = false;
    }
alert(list);

(为了避免混淆,我将把你的第一个数组称为dates而不是array

基本上有两种选择:

  1. 遍历dates数组,对于每个条目,遍历objArray以查找匹配项,并在找到时添加到priceResult数组中,或者

  2. 根据 objArray, then loop through your 日期array once, building the priceResult' 数组构建地图。

循环和循环

您可以使用 forEach 遍历dates数组,您可以使用 Array#some 来查明您的objArray是否包含日期并添加到priceResult如果是(这是一个 ES5 功能,但您可以为非常旧的浏览器填充它(:

var priceResult = [];
dates.forEach(function(date) {
    objArray.some(function(object) {
        if (object.date == date) {
            priceResult.push(object.price);
            return true;
        }
    });
});

Array#some 一直循环,直到您返回 true ,这就是为什么我们在找到第一个匹配时这样做的原因。这就是为什么我说这是"循环和循环",即使我们只写一个循环,另一个在Array#some内。

var dates = ['2014-10-09', '2014-10-10', '2014-10-11', '2014-10-12'];
var objArray = [
  {
    date: "2014-10-09",
    model: "A",
    price: "100"
  },
  {
    date: "2014-10-10",
    model: "A",
    price: "99"
  },
  {
    date: "2014-10-12",
    model: "A",
    price: "102"
  }
];
// Do it
var priceResult = [];
dates.forEach(function(date) {
  objArray.some(function(object) {
    if (object.date == date) {
      priceResult.push(object.price);
      return true;
    }
  });
});
snippet.log(priceResult.join(", "));
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>

映射和循环

首先,按日期创建价格地图:

var prices = {};
objArray.forEach(function(object) {
    prices[object.date] = object.price;
});

。然后创建结果:

var priceResult = [];
dates.forEach(function(date) {
    if (prices.hasOwnProperty(date)) {
        priceResult.push(prices[date]);
    }
});

var dates = ['2014-10-09', '2014-10-10', '2014-10-11', '2014-10-12'];
var objArray = [
  {
    date: "2014-10-09",
    model: "A",
    price: "100"
  },
  {
    date: "2014-10-10",
    model: "A",
    price: "99"
  },
  {
    date: "2014-10-12",
    model: "A",
    price: "102"
  }
];
// Create the map
var prices = {};
objArray.forEach(function(object) {
  prices[object.date] = object.price;
});
// Create your results:
var priceResult = [];
dates.forEach(function(date) {
  if (prices.hasOwnProperty(date)) {
    priceResult.push(prices[date]);
  }
});
// Show them
snippet.log(priceResult.join(", "));
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>

var dates = ['2014-10-09','2014-10-10','2014-10-11','2014-10-12'];
var objArray = [{date:"2014-10-09", model:"A", price:"100" }, {date:"2014-10-10", model:"A", price:"99" }, {date:"2014-10-12", model:"A", price:"102" }];
var val;
var priceResult = [];
for (var a in dates) {
    val = null;
    for (var b in objArray) {
        if (dates[a] == objArray[b].date) {
            val = objArray[b].price;
        }
    }
    priceResult.push(val);
}

    var dates = ['2014-10-09', '2014-10-10', '2014-10-11', '2014-10-12'];
    var objArray = [{
      date: "2014-10-09",
      model: "A",
      price: "100"
    }, {
      date: "2014-10-10",
      model: "A",
      price: "99"
    }, {
      date: "2014-10-12",
      model: "A",
      price: "102"
    }];
    var val;
    var priceResult = [];
    for (var a in dates) {
      val = null;
      for (var b in objArray) {
        if (dates[a] == objArray[b].date) {
          val = objArray[b].price;
        }
      }
      priceResult.push(val);
    }
     // output result in StackOverflow snippet
    document.write(JSON.stringify(priceResult));

试试这个:

var temp[] 
temp= jQuery.grep(objArray , function (n, i)
 { 
    for(j=0;j<dateArray.lenght+j++ )
        if( n.date === dateArray[j])
            return n.price;
 );
dateArray = ["2014-10-09", "2014-10-10", "2014-10-11", "2014-10-12"];
function ObjectExample(date1,model,price)
{
    this.date1 = date1;
    this.model = model;
    this.price = price;
}
var objArray = [new ObjectExample("2014-10-09","A","100"), new ObjectExample("2014-10-10","A","99"), new ObjectExample("2014-10-12","A","102")];
var i = 0;
var priceDate = new Array();
var count = 0;
while(i < dateArray.length)
{
    var j = 0;
    while(j < objArray.length)
    {
        if(dateArray[i] == objArray[j].date1)
        {
             priceDate[count] = objArray[j].price;
             break;
        }
        else priceDate[count] = "NULL";
        j = j + 1;
    }
    i = i + 1;
    count++;
}
document.write(priceDate);