簡體   English   中英

在JavaScript中將數組與對象數組進行比較

[英]Comparing an Array with an Objects' Array in JavaScript

我是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' ,因為它通常更易於處理。

(為了避免混淆,我將稱呼您的第一個數組dates而不是array 。)

基本上有兩種選擇:

  1. 遍歷dates數組,對於每個條目,遍歷objArray尋找匹配項,找到后添加到priceResult數組中,或者

  2. objArray, then loop through your構建一個地圖objArray, then loop through your dates array once, building the priceResult`數組。

循環播放

您可以使用forEach遍歷dates數組,並且可以使用Array#some來查找objArray是否包含日期,如果是,則將其添加到priceResult (這是ES5功能,但您可以對真正的舊瀏覽器進行priceResult ):

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

Array#some一直循環播放,直到您返回true為止,這就是為什么當我們找到第一個tmatch時才這樣做。 這就是為什么我說這是“循環和循環”的原因,即使我們只編寫一個循環,另一個也位於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> 

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

嘗試這個:

var temp[] 

temp= jQuery.grep(objArray , function (n, i)

 { 
    for(j=0;j<dateArray.lenght+j++ )
        if( n.date === dateArray[j])
            return n.price;
 );

循環遍歷對象並在數組中搜索日期

// 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);
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)); 

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);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM