在js中修改对象数组里面的对象数组

问题描述

开发人员您好,我正在尝试在将结果部署到 Redux reducer 之前修改对象数组中的对象数组。 该数组是通过对端点的请求获得的,为什么我必须创建它的可写副本的实例,然后继续该过程

不要说我有这个数组:

 allProducts=    [
            {
               
                "product_type": "Bikes","product_imgs": [
                    {
                        "id": 5,"url": "Mountain Bike/Screenshot (200)"
                    },{
                        "id": 6,"url": "Mountain Bike/Screenshot (200)"
                    }
                ],"product_name": "product test 1"
            },{
               
                "product_type": "Bikes","product_imgs": [
                    {
                        "id": 7,"url": "City Bike/banderaa"
                    },{
                        "id": 8,"url": "City Bike/banderaa"
                    }
                ],"product_name": "product test 2"
            }
       ]

我想修改每个对象的数组 product_imgs 中的项目,但为此,请记住这个数组来自一个请求,我确实创建了一个可读的副本并设置了逻辑。

let instance=[...allProducts];

然后为每个使用双倍(尽管我也尝试使用双倍循环),直到每个对象的对象数组 product_imgs 中的每个图像为止:

        instance.forEach(array=>array.product_imgs.map(element => {
          
          this.imgDownLoaderFirebase
          .ref(element.url)
          .getDownloadURL()
          .toPromise()
          .then((url) => {
            console.log(url);
            
            //then in this space once the url of some firebase endpoint is reached and else 
            //i would like to modify that object inside the array product_imgs which is at the same time 
            //part of the instance array.
            //For that i expose that this new url gotten would be asigned as the new 
            //value thus
            
            element = { ...element };
            element.url=url
            
            console.log(element);
            console.log(instance);//Printing the general array in order to check if changes committed
           
          })
       })

        

我想指定我首先使用 foreach 然后使用 map 以修改对象的内部数组 result ,但是为 each 使用 double 并不能精确地改善这种情况:

instance.forEach(array=>array.product_imgs.forEach(element => {........

然后查看日志,对象数组的对象数组product_imgs里面的元素(item url)被修改了,但是包含内部的外部数组没有修改

enter image description here

我该如何改进? 谢谢

解决方法

如果您的目标是从数组中提取所有 product_img 值,您可以尝试以下操作:

// This line will convert your array of object into an array of array of urls,using a destructuring process
const urls = allProducts.map(({ product_img }) => product_img);

// This line will merge the previous result into a single-level array of urls that you can iterate onto.
const result = [].concat([],...res);

编辑:我忘了提到这个过程实际上会返回一个包含你的 id 和 url 的对象数组。