【问题标题】:Find and update value in array of nested objects在嵌套对象数组中查找和更新值
【发布时间】:2017-04-04 09:13:55
【问题描述】:

我有一个对象数组如下:

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

    }
  }, ...
]

...以及我要应用的参数更改数组,例如:将 size 更改为 189 where product.specifications.attributes.parameters.id == 199199。

我想在不展平任何元素的情况下执行此操作,因为它们是 Vue.js 数据结构的一部分,它会破坏反应性。

我怎么能这样做?我愿意使用 Underscore 或 lo-dash

【问题讨论】:

    标签: javascript underscore.js vue.js lodash


    【解决方案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/

    【讨论】:

    • 非常好。由于参数 id 是唯一的,我应该在更改大小后中断吗?根据stackoverflow.com/questions/183161/…
    • 在屏幕上对大约 5000 种产品进行了测试,我选择了您的答案,因为与 stasovlas 提交的数据相比,更新所有数据所需的时间似乎少了几毫秒。更新后会尝试打破循环,这将节省更多的循环,因为产品只显示一次。
    • @NickM 不幸的是,Array.prototype.map 没有内置的中断选项。除非您拥有大量的项目,否则您可能不会看到性能上有太大差异。
    【解决方案2】:
    _.forEach(products, function(product) {
        _.forEach(_.get(product, 'specifications.attributes', []), function(attribute) {
            _.set(_.find(attribute.parameters, {id: 199199}), 'size', 189);
        });
    });
    

    【讨论】:

    • 如果产品没有“属性”键,它不会抛出吗?
    • 另外,.map 会生成一个新数组,这不是我想要的...可以用 .selects 链和 .extend({ size: 189 }) 或其他东西重写吗那些线?编辑“就地”值
    【解决方案3】:

    我相信你想要的是下划线的findIndex() - http://underscorejs.org/#findIndex。一旦您找到要应用更改的数组中的哪个元素(将嵌套 id 与您要查找的内容进行比较),您就可以对该特定元素进行更改。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-09-10
      • 1970-01-01
      • 2018-01-02
      • 2021-11-27
      • 2016-07-27
      • 1970-01-01
      • 2017-12-24
      相关资源
      最近更新 更多