json 如何使用Javascript获取属性链接的所有值并将值保存到新数组中?[closed]

qyzbxkaa  于 2022-12-01  发布在  Java
关注(0)|答案(2)|浏览(92)

已关闭。此问题需要更多focused。当前不接受答案。
**想要改进此问题吗?**更新问题,使其仅关注editing this post的一个问题。

昨天关门了。
Improve this question
json数据

const json = [{
      link: "animal",
      type: [{
            link: "animal/dog"
         },
         {
            link: "animal/cat",
            type: [{
                  link: "animal/cat/savannah"
               },
               {
                  link: "animal/cat/bombay"
               }
            ]
         }
      ]
   },
   {
      link: "car",
      type: [{
            link: "car/dodge"
         },
         {
            link: "car/mazda",
            type: [{
               link: "car/mazda/mx5"
            }]
         }
      ]
   }
];
iqjalb3h

iqjalb3h1#

我们可以使用Array.forEach()结合递归函数来做这

let convertData = (data) => {
   let result = []
   data.forEach(d => {
     result.push(d.link)
     if(d.type){
        result.push(...convertData(d.type))
     }
   })
   return result
} 

console.log(convertData(json))
const json = [{
      link: "animal",
      type: [{
            link: "animal/dog"
         },
         {
            link: "animal/cat",
            type: [{
                  link: "animal/cat/savannah"
               },
               {
                  link: "animal/cat/bombay"
               }
            ]
         }
      ]
   },
   {
      link: "car",
      type: [{
            link: "car/dodge"
         },
         {
            link: "car/mazda",
            type: [{
               link: "car/mazda/mx5"
            }]
         }
      ]
   }
]

let convertData = (data) => {
   let result = []
   data.forEach(d => {
     result.push(d.link)
     if(d.type){
        result.push(...convertData(d.type))
     }
   })
   return result
} 

console.log(convertData(json))
tvokkenx

tvokkenx2#

您可以使用递归来解决这个问题。

const getLinks = (json, arr = []) => {
    json.forEach(item => {
        arr.push(item.link);
        if(item.type){
            getLinks(item.type, arr);
        }
    });
    return arr;
}

console.log(getLinks(json));

说明:getLinks采用两个参数:jsonarrarr是初始化为空数组的数组。
然后使用forEach循环遍历json数组,并将link属性的值推入arr数组。
如果item具有type属性,则再次调用函数getLinks,将item.type作为第一个参数,将arr数组作为第二个参数。

相关问题