在Javascript中比较对象和数组

时间:2017-06-27 10:06:48

标签: javascript arrays

基于某些键比使用for loop

更好更简单地比较对象和数组

示例:

var Obj = {
  ID: "27374b25-a97b-4676-889b-32d87087c72d",
  Name: "Kenny J. Jones",
  City: "Dallas, TX"
};
var Array = [{
    ID: "27374b25-a97b-4676-889b-32d87087c72d",
    Name: "Kenny J. Jones",
    City: "Dallas, TX"
  },
  {
    ID: "50d861e8-793f-4d6c-87f4-09cf7312310f",
    Name: "Denise L. Demeo",
    City: "Pine, LA 70438"
  },
  {
    ID: "95a03cda-5f26-4b60-b070-e92885f1a9b7",
    Name: "Jose A. Steed",
    City: "Florence, SC 29501"
  }
];

for (var i = 0; i < Array.length; i++) {
  if (Obj.ID === Array[i].ID) {
    Array[i].Person = true;
  }
}
console.log(Array);

如果我在此数组中有10.000个对象,该怎么办?这对性能有害吗?

3 个答案:

答案 0 :(得分:0)

更紧凑和相同的性能:

var Obj = {
  ID: "27374b25-a97b-4676-889b-32d87087c72d",
  Name: "Kenny J. Jones",
  City: "Dallas, TX"
};
var myArray = [{
    ID: "27374b25-a97b-4676-889b-32d87087c72d",
    Name: "Kenny J. Jones",
    City: "Dallas, TX"
  },
  {
    ID: "50d861e8-793f-4d6c-87f4-09cf7312310f",
    Name: "Denise L. Demeo",
    City: "Pine, LA 70438"
  },
  {
    ID: "95a03cda-5f26-4b60-b070-e92885f1a9b7",
    Name: "Jose A. Steed",
    City: "Florence, SC 29501"
  }
];

myArray.filter(x => x.ID === Obj.ID).forEach(x => {
  x.Person = true;
});

console.log(myArray)

答案 1 :(得分:0)

更多优化, 获得匹配后,请使用中断

var end = Array.length;
var i = 0 
for (i; i < end i++) {
  if (Obj.ID === Array[i].ID) {
    Array[i].Person = true;
    break;
  }
}

答案 2 :(得分:0)

@Test
public void test() {

    Set<Integer> set = new HashSet<Integer>(Arrays.asList(2, 1, 3));
    Set<Integer> expected = new HashSet<Integer>(Arrays.asList(3, 2, 1));

    assertEquals(set, expected);
}

首先,使用const obj = { Id: "27374b25-a97b-4676-889b-32d87087c72d", Name: "Kenny J. Jones", City: "Dallas, TX" }; const arr = [ { Id: "27374b25-a97b-4676-889b-32d87087c72d", Name: "Kenny J. Jones", City: "Dallas, TX" }, { Id: "50d861e8-793f-4d6c-87f4-09cf7312310f", Name: "Denise L. Demeo", City: "Pine, LA 70438" }, { Id: "95a03cda-5f26-4b60-b070-e92885f1a9b7", Name: "Jose A. Steed", City: "Florence, SC 29501" } ]; 方法查看是否有Array.prototype.findIndex()个条目与arr具有完全相同的Id。使用此方法的优点是,一旦找到匹配,它就会停止查看。

obj

如果匹配,const index = arr.findIndex(entry => entry.Id === obj.Id); 将存储匹配的位置,可用于将index的键添加到该位置的对象并将其设置为true。

person