Sunday, July 8, 2018

javascript - Find and update value in array of nested objects



I have an object array as follows:



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
}, ...
]
}, ...
]

}

}, ...
]


... and an array of changes to parameters I want to apply, for example: change size to 189 where product.specifications.attributes.parameters.id == 199199.



I'd like to do this without flattening any elements as they are part of a Vue.js data structure, it will break the reactivity.



How could I do this? I am open to using Underscore or lo-dash


Answer




This looks ugly, but it is effective:



To make it more dynamic, let's use variables: identifier will be your '199199' value and new_size for the '189' value.



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;

})
});
});
}
}


Here is a working fiddle: https://jsfiddle.net/crabbly/eL7et9e8/


No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...