如何检查对象之间的字段值(存储在关联数组中)是否相等?

How to check if fields values between objects (stored within an associative array) are equal?

假设我有 this 代码:

var denti={}

function Dente() {
    this.ID = "";
    this.Tipologia = "";
    this.Lavorazione = "";
}

var dente = new Dente();
dente.ID="id1";
dente.Tipologia="tipo1";
dente.Lavorazione="lavoro1";
denti[dente.ID] = dente;

dente = new Dente();
dente.ID="id2";
dente.Tipologia="tipo1";
dente.Lavorazione="lavoro2";
denti[dente.ID] = dente;

dente = new Dente();
dente.ID="id3";
dente.Tipologia="tipo1";
dente.Lavorazione="lavoro1";
denti[dente.ID] = dente;

我需要检查所有字段 TipologiaLavorazione 是否相同。

在这种情况下,我要求的函数CheckArrayTipologia()应该returntrue(所有.Tipologia字段值都相同,tipo1)。

相反,CheckArrayLavorazione()应该returnfalse(他们不都是lavoro1,还有一个lavoro2)。

你如何在 Javascript/jQuery 中快速做到这一点?

这解决了您的问题:

function CheckArrayTipologia() {
    var tipologia;

    for (dente in denti) {
        if (!tipologia) {
            tipologia = dente.Tipologia;
            continue;
        }

        if (tipologia !== dente.Tipologia) {
            return false;
        }
    }

    return true;
}

DEMO

或使用 Lodash,更短:

function CheckArrayTipologia() {
    var values = _.values(denti);
    return _.every(values, 'Tipologia', _.first(values).Tipologia);
}

DEMO

你可以尝试用every函数

检查一下
var patternID = 'id1';

var res = Object.keys(denti).every(id => 
    denti[id].Lavorazione == denti[patternID].Lavorazione &&
    denti[id].Tipologia == denti[patternID].Lavorazione);

如果您不介意使用 Underscore.js 那么您可以这样做:

var tipologias = _.map(denti, function(d) { 
    return d.Tipologia; 
});
var areAllTipologiasEqual = _.uniq(tipologias).length === 1;

对@GG 解决方案进行一些改动,使其更快

function CheckArrayTipologia() {
    var lastTipologia;

    for (dente in denti) {
        if (!lastTipologia) {
            lastTipologia = dente.Tipologia;
            continue;
        }

        if (lastTipologia !== dente.Tipologia) {
            return false;
        }
    }

    return true;
}

首先,我建议使用数组来存储您的对象 - 如果您需要从对象的 ID 中获取对象,您可以使用 filter.

var denti = [];

我重写了您的构造函数,以便您传入一个参数对象并将其属性设置为新的对象属性:

function Dente(params) {
  for (var p in params) {
    this[p] = params[p];
  }
}

现在只需定义一个新对象并立即将其推入数组:

denti.push(new Dente({
  id: 'id1',
  Tipologia: 'tipo1',
  Lavorazione: 'lavoro1'
}));

然后您可以编写一个通用函数,将数组和要检查的对象的 属性 传递到其中:

function checkSame(arr, prop) {
  if (!arr.length) return false;

  // extract the property values from each object
  return arr.map(function (el) {
    return el[prop];

  // Check if they're all the same
  }).every(function (el, i, arr) {
    return el === arr[0];
  });
}

checkSame(denti, 'Tipologia'); // true
checkSame(denti, 'Lavorazione'); // false

DEMO

或者功能稍强的JS(ES6):

const pick = (prop) => obj => obj[prop];
const same = (el, i, arr) => el === arr[0];
const checkSame = (arr, prop) => arr.map(pick(prop)).every(same);

DEMO