【问题标题】:Concat the value of object key with the value of all the previous objects with the same key inside of a state array将对象键的值与状态数组中具有相同键的所有先前对象的值连接起来
【发布时间】:2022-11-30 08:47:36
【问题描述】:

我有一个对象状态数组,我想将一个对象的每个 URL 与它之前对象的所有 URL 连接起来:

    navigation:[    
     {
        "type": "LINK",
        "uri": "arbress"
    },
    
    {
        "type": "LINK",
        "uri": "arbres-a-grand-developpement"
    },

    {
        "type": "LINK",
        "uri": "Acer-xfreemanii"
    }
  ]

我希望结果是这样的:

navigation:[    
         {
            "type": "LINK",
            "uri": "arbress"
        },
        
        {
            "type": "LINK",
            "uri": "arbress/arbres-a-grand-developpement"
        },

        {             
            "type": "LINK",
            "uri": "arbress/arbres-a-grand-developpement/Acer-xfreemanii"
        }
      ]

这是我的代码,但没有任何改变,我总是得到初始状态:

useEffect(() => {
        const newState = navigation.map((obj1) => {
            if(obj1.type === 'LINK'){
                navigation.map((obj2) => {
                    if (obj2 === 'LINK'){
                        return {...obj1, uri: obj2.uri+"/"+uri}
                    }
                })
            }
            return obj1;
        })

        setNavigation(newState)
    }
  }, [])

【问题讨论】:

    标签: javascript reactjs arrays state


    【解决方案1】:

    使用在 .map 回调中迭代的索引,这样您就可以将 navigation 数组从 0 切片到索引,然后加入每个先前对象的 uris。

    useEffect(() => {
      setNavigation(
        navigation
          .filter(obj => obj.type === 'LINK')
          .map((_, i, arr) => ({
            type: 'LINK',
            uri: arr
              .slice(0, i + 1) // include this item being iterated over in the result
              .map(obj => obj.uri)
              .join('/'),
          }))
      );
    }, []);
    

    【讨论】:

      猜你喜欢
      • 2022-06-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-01-26
      • 2022-11-18
      相关资源
      最近更新 更多