【问题标题】:Change all keys in array also deeper inside object with array使用数组更改数组中的所有键也更深入的对象内部
【发布时间】:2020-11-09 14:21:58
【问题描述】:

目前对于我们的导航结构,我们有以下数组:

 {
  childNodes: [
   {title: "Mijn afdeling", type: "Department", relativeUri: "/mijnafdeling"},
   {title: "contact", type: "Department", relativeUri: "/contact"}
  ]
  RelativeUri: '/',
  title: 'test'
 },
{
  childNodes: null
  RelativeUri: '/',
  title: 'test'
 }
]

现在我想将所有 'childNodes' 键更改为 'child' 并将所有 relativeUri 键更改为 href。

我想要的结果应该是

 {
  child: [
   {title: "Mijn afdeling", type: "Department", href: "/mijnafdeling"},
   {title: "contact", type: "Department", href: "/contact"}
  ]
  href: '/',
  title: 'test'
 },
{
  child: null
  href: '/',
  title: 'test'
 }
]

我知道我可以执行类似this.navigationArray = this.navigationArray.map(({ childNodes, relativeUri }) => ({ childNodes: child, href: relativeUri })) 的操作,但是我也不知道如何获取 childNodes 对象下数组中的所有键。所以它基本上需要“查找”或遍历数组中的所有对象,并找到特定的键。 'childNodes' 对象也可以为 null。

对于不同的页面,我有不同数量的导航项,所以我宁愿不针对特定的索引,因为这会扰乱导航。

非常感谢!

【问题讨论】:

    标签: arrays loops dictionary key


    【解决方案1】:

    应该这样做:

    const nu = orig
        .map(
            ({
                childNodes,
                RelativeUri,
                title
            }) => ({
                child: childNodes ?
                    childNodes.map(({
                        title,
                        type,
                        relativeUri
                    }) => ({
                        title,
                        type,
                        href: relativeUri
                    })) : childNodes,
                href: RelativeUri,
                title
            }));
    
    console.log(nu);
    

    演示

    const orig = [
        {
            childNodes: [{
                    title: "Mijn afdeling",
                    type: "Department",
                    relativeUri: "/mijnafdeling"
                },
                {
                    title: "contact",
                    type: "Department",
                    relativeUri: "/contact"
                }
            ],
            RelativeUri: '/',
            title: 'test'
        },
        {
            childNodes: null,
            RelativeUri: '/',
            title: 'test'
        }
    ];
    
    //console.log( orig );
    
    const nu = orig
    .map(({childNodes,RelativeUri,title}) => ({child: childNodes ? childNodes.map(({title,type,relativeUri}) => ({title,type,href:relativeUri})) : childNodes, href:RelativeUri, title}));
    
    console.log( nu );

    【讨论】:

      猜你喜欢
      • 2019-07-31
      • 2022-01-18
      • 2020-08-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-10-23
      • 2011-10-12
      相关资源
      最近更新 更多