代码之家  ›  专栏  ›  技术社区  ›  Sujoy Saha

更新嵌套对象

  •  -1
  • Sujoy Saha  · 技术社区  · 6 年前

    如何更新特定数组元素的值?

    let data = [
     {title: 'food', category: 'food', value: 10},
     {title: 'good', category: 'hood', value: 40},
     {title: 'sood', category: 'lending', value: 20},
    ]
    
    1 回复  |  直到 6 年前
        1
  •  0
  •   yez    6 年前
    • data[1].value = "aValue"

    • 要更新标题为“食品”的所有项目: data.filter(e => e.title === "food").forEach(e => e.value = "aValue" )

    • 要更新“hood”类别的所有项目,请执行以下操作: data.filter(e => i.category === "hood").forEach(e => e.value = "aValue" )

        2
  •  0
  •   Sajeeb Ahamed    6 年前

    您的问题太短,无法理解,但您可以尝试通过查找并使用此函数替换对象来更新任何对象。

      let data = [
         {title: 'food', category: 'food', value: 10},
         {title: 'good', category: 'hood', value: 40},
         {title: 'sood', category: 'lending', value: 20},
      ];
    
    /**
    * By this function you can update any array of objects and return the * updated array.
    *
    * @param    array    data         The data array to update.
    * @param    string   findKey      The key to select the object to update.
    * @param    string   findValue    The value which has to match for object selection.
    * @param    string   replaceKey   Which key to update.
    * @param    string   replaceValue replaceKey updated by which value.
    *
    * @return   array    The updated array.
    */
    function update(data, findKey, findValue, replaceKey, replaceValue) {
      return data.map(value => {
        
        if (value[findKey] === findValue) {
          value[replaceKey] = replaceValue;
        }
        
        return value;
      });
    }
    
    // Here I update the data array by finding the object which has the 'title' value is 'food' and replace the 'value' field by 50
    const updatedData = update(data, 'title', 'food', 'value', 50);
    
    console.log(updatedData);
        3
  •  0
  •   Mnikoei    6 年前

    简单地说:

     arr.map((obj) => {
    
      if(obj.value === 'Old value'){
         obj.value = 'New value'; 
      }
    
      return obj;
    
     })