【问题标题】:Update the object value based on array index [closed]根据数组索引更新对象值 [关闭]
【发布时间】:2025-12-08 00:20:03
【问题描述】:

我在数组中有 2 个对象

dataV[1] = {
            "resolution": "4"
        };

datas[1] = {
     {qty_approved: "1", resolution: "5", status: "", order: "1332"}
}

如果两个索引相同,那么我想使用第一个的值进行更新。我想将分辨率值从 5 更新为 4。基于 dataV 中新数组值的即将到来的值

这样的预期输出:

datas[1] = {
     {qty_auth: "1", resolution: "4", status: "", order: "1332"}
}

【问题讨论】:

  • dataVdatas 的完整值是多少?
  • dataV 是动态的,每次分辨率值都会根据下拉值@MajedBadawi 更新
  • 它们是对象还是数组?
  • dataV 和 datas 是数组,在该对象内部类似于 1: {qty_approved: "1", resolution: "4", status: "", order_item_id: "1332"} @Majed Badawi
  • 我已经在这里详细发布了我的问题:[*.com/questions/69808608/…所以我现在部分隔离以获得更好的响应

标签: javascript arrays reactjs object


【解决方案1】:

无论您在哪里更新 dataV 的值,您都可以执行以下操作来更新 datas

datas = datas.map((data, i) => {
  return { ...data, resolution: dataV[i].resolution };
});

如果您使用react,您可以在useEffect 中使用dataV 作为依赖项执行相同的操作。所以,每当dataV 改变时,datas 就会自动改变。

【讨论】:

  • 我正在使用类组件,当我在每次删除值时尝试使用状态时,所以我在全局中使用 var 进行处理。 @Shakirul Hasan
  • 那你可以试试我上面写的流程。
  • 如果数据数组不存在特定索引怎么办?那么我该如何检查它的状况呢? @Shakirul Hasan
【解决方案2】:
let array1 = [
    {
        resolution: '4',
    },
];

let array2 = [
    { qty_approved: '1', resolution: '5', status: '', order: '1332' },
];

let array3 = array1.map((element, index) => {
    if (typeof array2[index] != 'undefined') {
        return { ...array2[index], ...element};
    }
    return element;
});

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax

【讨论】:

    【解决方案3】:

    由于可以通过数组索引得到对应的元素,所以可以很简单的得到对应的分辨率,如下sn-p:

    datas.forEach( (_, i) => {
        datas[i].resolution = dataV[i].resolution
    })
    

    【讨论】:

      【解决方案4】:
      • 使用Array#reduce,迭代dataV,同时更新Map,其中索引为key,分辨率为value
      • 使用Array#forEach,遍历datas,如果上面的map有这样索引的key,更新分辨率

      const 
        dataV = [ { "resolution": "4" }, { "resolution": "7" }, { "resolution": "1" } ],
        datas = [
          { qty_approved: "1", resolution: "5", status: "", order: "1332" },
          { qty_approved: "1", resolution: "3", status: "", order: "1331" },
          { qty_approved: "1", resolution: "9", status: "", order: "1333" },
        ];
      
      const indexResolutionMap = dataV.reduce((map, { resolution }, i) =>
        map.set(i, resolution)
      , new Map);
      
      datas.forEach((e, i) => {
        const resolution = indexResolutionMap.get(i);
        if(resolution) e.resolution = resolution;
      });
      
      console.log(datas);

      【讨论】:

        【解决方案5】:

        下面的做法是去mapdatas的每一项。尽管如此,映射函数将是一个真正的函数(不是箭头函数),因此它知道 map's second thisArg 参数,对于 OP 的用例,该参数将是 dataV 数组,人们想要从中读取 resolution 值。

        这种方法的优点是,可以使用一个与外部数组引用无关的可重复使用的映射器函数,因为它确实处理了一个数组,而相关的/corresponding 数组作为映射器函数 this 上下文提供。

        映射功能本身会尝试通过创建整个项目的浅表副本来松散地解耦引用,从而不改变原始项目引用。在顶部,通过this[idx].resolution 从相应数组中读取的resolution 值被分配给刚刚创建的浅拷贝。

        const datas = [
          { qty_approved: "1", resolution: "5", status: "", order: "1332" },
          { qty_approved: "1", resolution: "3", status: "", order: "1331" },
          { qty_approved: "1", resolution: "9", status: "", order: "1333" },
        ];
        
        const dataV = [{
          "resolution": "4",
        }, {
          "resolution": "7",
        }, {
          "resolution": "1",
        }];
        
        // mapping approach.
        
        function copyItemAndAssignSameIndexResolutionFromTargetArray(item, idx) {
          // - this merge pattern is agnostic about an `item`'s structure.
          // - `item` could feature more keys but just `resolution` gets reassigned.
          return Object.assign({}, item, { resolution: this[idx].resolution });
        }
        console.log(
          'mapped version of changed `dataV` items ...',
          datas.map(copyItemAndAssignSameIndexResolutionFromTargetArray, dataV)
        );
        console.log('still unmutated `datas` ...', { datas });
        .as-console-wrapper { min-height: 100%!important; top: 0; }

        如果 OP 想要改变 datas 数组的每个项目,上面介绍的映射器函数会稍作更改,以便被上下文感知 forEach 使用...

        const datas = [
          { qty_approved: "1", resolution: "5", status: "", order: "1332" },
          { qty_approved: "1", resolution: "3", status: "", order: "1331" },
          { qty_approved: "1", resolution: "9", status: "", order: "1333" },
        ];
        
        const dataV = [{
          "resolution": "4",
        }, {
          "resolution": "7",
        }, {
          "resolution": "1",
        }];
        
        // mapping approach.
        
        function assignSameIndexResolutionFromTargetArray(item, idx) {
          item.resolution = this[idx].resolution;
          // Object.assign(item, { resolution: this[idx].resolution });
        }
        datas.forEach(assignSameIndexResolutionFromTargetArray, dataV);
        
        console.log('mutated `datas` array ...', { datas });
        .as-console-wrapper { min-height: 100%!important; top: 0; }

        或者(拼命猜测)OP 是否正在寻找一个解决方案,其中 datas 项目必须由明确提供的 dataV 项目更新/突变?像这样?..

        const datas = [
          { qty_approved: "1", resolution: "3", status: "", order: "1331" },
          { qty_approved: "1", resolution: "5", status: "", order: "1332" },
          { qty_approved: "1", resolution: "9", status: "", order: "1333" },
        ];
        
        const dataV = [{
          "resolution": "1",
        }, {
          "resolution": "4",
        }, {
          "resolution": "7",
        }, ];
        
        function updateResolution(targetArray, sourceArray, resolutionItem) {
          const updateIndex =
            sourceArray.findIndex(item =>
              item.resolution === resolutionItem.resolution
            );
          targetArray[updateIndex].resolution = resolutionItem.resolution;
        
          return targetArray[updateIndex];
        }
        
        console.log(
          'updateResolution(datas, dataV, { resolution: "4"}) ...',
          updateResolution(datas, dataV, { resolution: "4"})
        );
        console.log('mutated `datas` array ...', { datas });
        
        console.log(
          'updateResolution(datas, dataV, { resolution: "7"}) ...',
          updateResolution(datas, dataV, { resolution: "7"})
        );
        console.log('mutated `datas` array ...', { datas });
        .as-console-wrapper { min-height: 100%!important; top: 0; }

        【讨论】:

        • 我不明白这个@Peter
        • @ShantalKaula ... 完成。提供了解释、文档链接和第二个变异方法。
        • @ShantalKaula ...查看最新尝试。如果到目前为止尚未在所有提供的答案中找到正确的方法/解决方案,我建议重新制定整个问题,以便以易于理解的方式详细解释问题,并附上更有意义的示例代码作为好吧。