[英]Check if certain Javascript object key has exact nested values and then update specific nested value
I have a Javascript object that can have either none, one, or multiple keys.我有一个 Javascript 对象,它可以没有、一个或多个键。 Then each key has a nested value.
然后每个键都有一个嵌套值。
Example例子
cart = {
"98eb9514-f403-4d08-b5f7-dd6a5ec013cb": {
"quantity": 1,
"FirstName": "John",
"LastName": "Lewis"
},
"92ef2918-6bc2-4f3b-b9b3-acf6ebe74b1f": {
"quantity": 1,
"FirstName": "Matthew",
"LastName": "Smith"
}
}
I need to check if a key has an exact nested value.我需要检查一个键是否有一个精确的嵌套值。 If it does, then I need to add 1 to the quantity for that exact key with that exact nested value.
如果是这样,那么我需要将具有该精确嵌套值的该精确键的数量加 1。
I am able to check if an exact key with that exact nested value exist by doing:我可以通过执行以下操作来检查是否存在具有该精确嵌套值的精确键:
if (cart.hasOwnProperty(productId) &&
cart[productId]["quantity"] >= 1 &&
cart[productId]["FirstName"] == FirstName &&
cart[productId]["LastName"] == LastName) {
console.log('add one to qty somehow...')
}
However, this seems very inefficient and then I can't even figure out a way to add one to the quantity for just that exact key with that exact nested value.但是,这似乎非常低效,然后我什至无法找到一种方法来为具有该精确嵌套值的精确键的数量添加一个。
If it is not clear, my question comes down to this: How do I check if a key with an exact nested value exist, and if it does, how do I add 1 to the quantity for that same exact key/nested value.如果不清楚,我的问题归结为:如何检查是否存在具有精确嵌套值的键,如果存在,我如何为相同的精确键/嵌套值在数量上加 1。
Been working on this for a day and half.已经为此工作了一天半。 Any help is much appreciated.
任何帮助深表感谢。
You could do it like this:你可以这样做:
const cart = { "98eb9514-f403-4d08-b5f7-dd6a5ec013cb":{"quantity":1,"FirstName":"John", "LastName":"Lewis"}, "92ef2918-6bc2-4f3b-b9b3-acf6ebe74b1f":{"quantity":1,"FirstName":"Matthew", "LastName":"Smith"} } const productId = "92ef2918-6bc2-4f3b-b9b3-acf6ebe74b1f"; const firstName = "Matthew"; const lastName = "Smith"; const quantity = 1; const cartItem = cart[productId]; if(typeof cartItem !== "undefined" && cartItem.FirstName === firstName && cartItem.LastName === lastName && cartItem.quantity >= 1) { cartItem.quantity += 1; }; console.log(cart);
Once you have a handle on the intended cart property, you can simply increment its quantity
property.一旦您掌握了预期的购物车属性,您就可以简单地增加其
quantity
属性。
let cart = { "98eb9514-f403-4d08-b5f7-dd6a5ec013cb": { "quantity": 1, "FirstName": "John", "LastName": "Lewis" }, "92ef2918-6bc2-4f3b-b9b3-acf6ebe74b1f": { "quantity": 1, "FirstName": "Matthew", "LastName": "Smith" } } let productId = '98eb9514-f403-4d08-b5f7-dd6a5ec013cb'; // any product key let valueToMAtch = 1; // any value to match let productKey = Object.keys(cart).find((key) => key === productId); Object.entries(cart[productKey] || {}).forEach(([key, value]) => { // || {} allows undefined handing if no product is found if (value === valueToMAtch) { cart[productKey][key] += 1; // adding one } }); console.log(cart); // result
If you're comparing thousands of records to thousands of other records, might want to pack it up somehow - the intent here, though, is it to de-dupe?如果您将数千条记录与数千条其他记录进行比较,可能想以某种方式将其打包 - 但是,这里的意图是重复数据删除吗?
If so, you could try something like...如果是这样,您可以尝试类似...
var cartCounter = {};
for (var itemKey in cart) {
var item = cart[itemKey];
var key = item.FirstName + "|" + item.LastName;
if (!cartCounter[key]) {
cartCounter[key] = item;
} else {
cartCounter[key].quantity++;
}
}
If you need deep equality based on enumerable properties only (that is: the values that you get when you use for...of
, or Object.keys
, etc.) then you can determine equality based on the JSON serialization of those objects, provided you force key sorting , using the rarely talked about replacer
argument for JSON.stringify()
.如果您只需要基于可枚举属性的深度相等(即:当您使用
for...of
或Object.keys
等时获得的值),那么您可以根据这些对象的 JSON 序列化来确定相等性,只要你强迫键排序,使用很少谈及replacer
参数为JSON.stringify()
This is an incredibly powerful feature of the JSON serialization process, and we can write a simple function that will guarantee any object we pass in will always serialize to the same JSON string, regardless of key ordering at any depth:这是 JSON 序列化过程的一个非常强大的功能,我们可以编写一个简单的函数来保证我们传入的任何对象始终序列化为相同的 JSON 字符串,无论在任何深度的键顺序如何:
function sortedObjectKeys(_, data) {
// Ignore primitives.
if (data === null) return null;
if (typeof data !== "object") return data;
// Also ignore iterables, which are type "object" but
// should not be sorted because [1,2,3] is not [1,3,2].
if (data.__proto__[Symbol.iterator]) return data;
// Then sort the object keys and yield a new object with that
// ordering enforced by key insertion.
return Object.fromEntries(Object.entries(data).sort());
}
We can now perform a deep equality test using string equality:我们现在可以使用字符串相等来执行深度相等测试:
function deepEqual(o1, o2) {
const s1 = JSON.stringify(o1, sortedObjectKeys);
const s2 = JSON.stringify(o2, sortedObjectKeys);
return s1 === s2;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.