[英]Javascript How to find a complete class object in an array
I have an array of objects that I use for a materials table datasource.我有一个用于材料表数据源的对象数组。 I need to see if this row already exists in the datasource array before adding it.在添加之前,我需要查看该行是否已存在于数据源数组中。
There is no key value in this array.此数组中没有键值。 So I need to check if all items are unique所以我需要检查所有项目是否都是唯一的
var datasource = [
{ Name: Jon, Address: 123 something }, {Name: Tyler , Address: 333 Something}
]
var rowtoAdd = [
{ Name: Jon, Address: 123 something }
]
const found = datasource.find(x => x.name == rowtoAdd.Name && x.Address == rowtoAdd.Address)
Is there a better way?有没有更好的办法?
One way you can do this is by hashing the elements.一种方法是对元素进行散列。 Your current solution takes O(n) time each time you need to check.每次需要检查时,您当前的解决方案都需要 O(n) 时间。 if you create a hashtable it will take 0(n) to create the table but the run time will O(1) for all consecutive run.如果您创建一个哈希表,则创建该表将花费 0(n),但所有连续运行的运行时间将为 O(1)。
var datasource = [
{ "Name": "Jon", "Address": "123 something" }, {"Name": "Tyler" , "Address": "333 Something"}
]
var map = datasource.reduce(function(map, obj) {
map[obj.Name+obj.Address] = true;
return map;
}, {});
rowtoAdd = { "Name": "Jon", "Address": "123 something" }
if(!map[rowtoAdd.Name+rowtoAdd.Address])
datasource.push(rowtoAdd)
So, in sort reduce your array to a hashmap所以,排序减少你的数组到一个哈希图
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.