在嵌套对象数组中查找和更新值
Find and update value in array of nested objects
我有一个对象数组如下:
products = [
{
id: 1,
title: "Product 1",
specifications: {
price: 1.55,
discount: 15,
attributes: [
{
l1: 100,
l2: 80
height:200,
weight: 15,
parameters: [
{
id: 199199 // this is how I identify the parameter
size: 185 // this is what I want to change
}, ...
]
}, ...
]
}
}, ...
]
... 以及我要应用的参数更改数组,例如:将大小更改为 189,其中 product.specifications.attributes.parameters.id == 199199.
我想在不展平任何元素的情况下执行此操作,因为它们是 Vue.js 数据结构的一部分,这会破坏反应性。
我该怎么做?我愿意使用 Underscore 或 lo-dash
我相信你想要的是下划线的findIndex()
- http://underscorejs.org/#findIndex。一旦找到数组中要应用更改的元素(将嵌套 ID 与您要查找的内容进行比较),您就可以对该特定元素进行更改。
_.forEach(products, function(product) {
_.forEach(_.get(product, 'specifications.attributes', []), function(attribute) {
_.set(_.find(attribute.parameters, {id: 199199}), 'size', 189);
});
});
这看起来很丑,但是很有效:
为了使其更具动态性,让我们使用变量:identifier
将是您的“199199”值,new_size
将是“189”值。
methods: {
updateRecord: function(identifier, new_size) {
this.products.map(function(product) {
product.specifications.attributes.map(function(attribute) {
attribute.parameters.map(function(parameter) {
if (parameter.id == identifier) parameter.size = new_size;
})
});
});
}
}
这是一个有效的 fiddle:https://jsfiddle.net/crabbly/eL7et9e8/
我有一个对象数组如下:
products = [
{
id: 1,
title: "Product 1",
specifications: {
price: 1.55,
discount: 15,
attributes: [
{
l1: 100,
l2: 80
height:200,
weight: 15,
parameters: [
{
id: 199199 // this is how I identify the parameter
size: 185 // this is what I want to change
}, ...
]
}, ...
]
}
}, ...
]
... 以及我要应用的参数更改数组,例如:将大小更改为 189,其中 product.specifications.attributes.parameters.id == 199199.
我想在不展平任何元素的情况下执行此操作,因为它们是 Vue.js 数据结构的一部分,这会破坏反应性。
我该怎么做?我愿意使用 Underscore 或 lo-dash
我相信你想要的是下划线的findIndex()
- http://underscorejs.org/#findIndex。一旦找到数组中要应用更改的元素(将嵌套 ID 与您要查找的内容进行比较),您就可以对该特定元素进行更改。
_.forEach(products, function(product) {
_.forEach(_.get(product, 'specifications.attributes', []), function(attribute) {
_.set(_.find(attribute.parameters, {id: 199199}), 'size', 189);
});
});
这看起来很丑,但是很有效:
为了使其更具动态性,让我们使用变量:identifier
将是您的“199199”值,new_size
将是“189”值。
methods: {
updateRecord: function(identifier, new_size) {
this.products.map(function(product) {
product.specifications.attributes.map(function(attribute) {
attribute.parameters.map(function(parameter) {
if (parameter.id == identifier) parameter.size = new_size;
})
});
});
}
}
这是一个有效的 fiddle:https://jsfiddle.net/crabbly/eL7et9e8/