Home > Software engineering >  How can I get all the values of the properties link and save values into a new array using Javascrip
How can I get all the values of the properties link and save values into a new array using Javascrip

Time:11-29

json data

    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"
            }]
         }
      ]
   }
];

CodePudding user response:

We can use Array.forEach() combined with recursively function to do it

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))

CodePudding user response:

You can solve this by using recursion.

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

console.log(getLinks(json));

Explanation: getLinks takes two parameters, json and arr. arr is an array that is initialized to an empty array.

Then using forEach loops through the json array and pushes the value of the link property into the arr array.

If the item has a type property, the function getLinks is called again with the item.type as the first parameter and the arr array as the second parameter.

  • Related