2016-11-21 186 views
2

我有一個對象數組的數組更新值如下:查找和嵌套對象

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數據結構的一部分,它會打破反應性。

我該怎麼做?我願意使用下劃線或下劃線

回答

1

這看起來醜陋,但它是有效的:

爲了使它更有活力,讓我們使用變量: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; 
       }) 
      }); 
     }); 
    } 
} 

這裏是工作提琴:https://jsfiddle.net/crabbly/eL7et9e8/

+0

非常好。由於參數ID是唯一的,我應該在更改大小後中斷嗎?根據http://stackoverflow.com/questions/183161/best-way-to-break-from-nested-loops-in-javascript –

+0

在屏幕上對5000個產品進行測試,我選擇了你的答案,因爲它看起來像與stasovlas提交的數據相比,我只需要幾個ms來更新所有的數據。嘗試在更新後打破週期,這將節省更多的週期,因爲產品只會顯示一次。 –

+0

@NickM不幸的是,Array.prototype.map沒有內置的中斷選項。除非你有大量的項目,否則你在性能上可能看不到太大的差異。 – crabbly

0

我相信你想要的是下劃線的findIndex() - http://underscorejs.org/#findIndex。一旦你找到數組中的哪一個元素,你就可以對這些變化進行應用(比較嵌套的id和你正在尋找的內容),然後你可以對這個特定的元素進行更改。

1
_.forEach(products, function(product) { 
    _.forEach(_.get(product, 'specifications.attributes', []), function(attribute) { 
     _.set(_.find(attribute.parameters, {id: 199199}), 'size', 189); 
    }); 
}); 
+0

請問如果一個產品不具備的「屬性」鍵,它不扔? –

+0

@NickM我編輯我的答案 – stasovlas

+0

此外,.map產生一個新的數組,這不是我想要的......這可以用一串.selects和.extend({size:189})重寫或沿着那些線?編輯值「in place」 –