Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find and update value in array of nested objects

Tags:

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

like image 426
Nick M Avatar asked Nov 21 '16 03:11

Nick M


1 Answers

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/

like image 184
crabbly Avatar answered Sep 26 '22 16:09

crabbly