JS中

时间:2018-05-05 17:01:07

标签: javascript arrays object recursion

我有一个包含可能具有n级深度的对象的数组。

这样的事情:

const settings = [

    {path: '/templates/pictures.php', url: '/pictures', label: 'Pictures', component: 'tab', template: 'default'},
    {path: '/templates/post-article.php', url: '/user/:username', component: 'table', template: 'default', children:[
        {path: '/templates/post-article-highlights.php', url: '/user/:username/highlights', component: 'table', template: 'default', children:[
              {path: '/templates/post-article-highlights.php', url: '/user/:username/highlights', component: 'table', template: 'default'}  

        ]}  
    ]}

]

我需要在不同的数组上推送'Url'属性和children属性(如果存在),但保留深度。

所以新数组应如下所示:

const newArray = [

    {url: '/pictures'},
    {url: '/user/:username', children:[
        {url: '/user/:username/highlights', children:[
                {url: '/user/:username/highlights'} 
        ]}  
    ]}

]

你能帮助我吗?

由于

3 个答案:

答案 0 :(得分:2)

您可以使用destructuring assignment获取所需的密钥,并使用Array#map获取仅包含一个属性的新数组,并通过检查子项使用Object.assign作为子项对象。存在,通过函数的递归调用从子节点中获取URL。



function getUrls(array) {
    return array.map(({ url, children }) =>
        Object.assign({ url }, children && { children: getUrls(children) }));
}

var settings = [{ path: '/templates/pictures.php', url: '/pictures', label: 'Pictures', component: 'tab', template: 'default' }, { path: '/templates/post-article.php', url: '/user/:username', component: 'table', template: 'default', children: [{ path: '/templates/post-article-highlights.php', url: '/user/:username/highlights', component: 'table', template: 'default', children: [{ path: '/templates/post-article-highlights.php', url: '/user/:username/highlights', component: 'table', template: 'default' }] }] }],
    urls = getUrls(settings);

console.log(urls);

.as-console-wrapper { max-height: 100% !important; top: 0; }




答案 1 :(得分:1)



const settings = [
    {path: '/templates/pictures.php', url: '/pictures', label: 'Pictures', component: 'tab', template: 'default'},
    {path: '/templates/post-article.php', url: '/user/:username', component: 'table', template: 'default', children:[
        {path: '/templates/post-article-highlights.php', url: '/user/:username/highlights', component: 'table', template: 'default', children:[
              {path: '/templates/post-article-highlights.php', url: '/user/:username/highlights', component: 'table', template: 'default'}  

        ]}  
    ]}
];


function childrenUrls(childrens){
	return childrens.reduce(function(arr, obj){
		var newObj = {url: obj.url};
		if(obj.children) newObj.children = childrenUrls(obj.children);
		return arr.push(newObj), arr;
	}, []);
}


const newArray = childrenUrls(settings);

console.log(newArray);




答案 2 :(得分:0)

这是一个简单易懂的方法 一个小提琴的例子,你可以进一步测试它:

https://jsfiddle.net/eugensunic/pftkosb9/

<?php    
include "db.php";

class Process extends Database
{
      public function verify_email($table,$email){
            //abc@gmail.com//
            $regexp = "/^[a-z0-9_-]+(\.[a-z0-9_-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$/";
            if(!preg_match($regexp,$email)){
            return "invalid_email";
         }
         //Check email already exists or not
            $sql = "SELECT id FROM ".$table." WHERE u_email = '$email' LIMIT 1";
            $query = mysqli_query($this->con,$sql);
            $count = mysqli_num_rows($query);
            if($count == 1){
                return "already_exists";
            }else{
                return "ok";
            }
        }


        public function insert_record($table,$input){
            $sql = "";
            $sql .= "INSERT INTO ".$table." ";
            $sql .= "(".implode(",",array_keys($input)).") VALUES ";
            $sql .= "('".implode("','", array_values($input))."')";
            $query = mysqli_query($this->con,$sql);
            $last_id = mysqli_insert_id($this->con);
            if($query){
                return $last_id;
        }
    } 
        public function send_activation_code($email,$act_code){

        }
}
$obj = new Process;

    if(isset($_POST["check_email"])){
       $email = $_POST["email"];
       echo $data = $obj->verify_email("user_info",$email);
       exit();
}

    if(isset($_POST["u_email"])){
    echo $name = preg_replace("#[^A-Za-z]#i", "", $_POST["u_name"]);
    echo $age = preg_replace("#[^0-9]#", "", $_POST["age"]);
    echo $dateofbirth = preg_replace("#[^0-9]#", "", $_POST["dob"]);
    echo $gender = preg_replace("#[^a-z ]#i", "", $_POST["gender"]);
    echo $educationalqualification = preg_replace("#[^0-9A-Za-z ]#", "", $_POST["edq"]);
    $lang = $_POST["lang"];
    $count = COUNT($lang);
    $languages = "";
    for($i=0;$i<$count;$i++){
        $languages .= $lang[$i].",";
    }
    $languages = substr($languages, 0, -1);
    echo $languages = preg_replace("#[^A-Za-z,]#i", "", $languages);
    echo $mobile  = preg_replace("#[^0-9]#", "", $_POST["mobile"]);
    echo $whatsapp = preg_replace("#[^0-9]#", "", $_POST["whatsapp"]);
    echo $pincode = preg_replace("#[^0-9]#", "", $_POST["pincode"]);
    echo $district = preg_replace("#[^A-Za-z]#i", "", $_POST["district"]);
    echo $states = preg_replace("#[^A-Za-z]#i", "", $_POST["state"]);
    echo $country = preg_replace("#[^A-Za-z]#i", "", $_POST["country"]);
    echo $others = preg_replace("#[^A-Za-z]#i", "", $_POST["others"]);
    $data = $obj->verify_email("user_info",$_POST["u_email"]);
    if($data == "already_exists"){
        echo "Email Already Exists";
        exit();
    }else{
        echo $email = $_POST["u_email"];
    }
    echo $currentoccupation = preg_replace("#[^A-Za-z]#i", "", $_POST["current"]);
    echo $workexperience = preg_replace("#[^A-Za-z]#i", "", $_POST["work"]);
    echo $username = preg_replace("#[^A-Za-z0-9]#", "", $_POST["username"]);
    echo $password = $_POST["password"];
    echo $repassword = $_POST["repassword"];


    //Start Validation from here
    if(empty($name) || empty($age) || empty($dob) ||  empty($gender) ||   empty($educationalqualification) ||  empty($languages) || 
    empty($mobile) ||  empty($whatsapp) ||  empty($pincode) ||  empty($district) ||  empty($state) ||  empty($country) ||  
    empty($currentoccupation) || empty($workexperience) || empty($username) || empty($password)){
          echo "empty_fields";
        exit();
    }

        if(strlen($password) < 9){
        echo "password_too_short";
        exit();
    }
    if($password != $repassword){
        echo "password_not_same";
        exit();
    }else{
      //hash password
        $options = array('cost' => 12,);
        echo $hash_password =  password_hash($password,PASSWORD_DEFAULT, $options);
    }
    $signup_date = date("Y-m-d H:i:s");
    $act_code = time().md5($email).rand(50000,1000000);
    $act_code = str_shuffle($act_code);
    $user = array("u_name"=>$name,"dob"=>$dateofbirth,"age"=>$age,"gender"=>$gender,"edq"=>$educationalqualification,"languages"=>$languages,"mobile"=>$mobile,"whatsapp"=>$whatsapp,"pincode"=>$pincode,"district"=>$district,"state"=>$states,"country"=>$country,"u_email"=>$email,"current"=>$currentoccupation,"work"=>$workexperience,"username"=>$username,"password"=>$hash_password,"signup_date"=>$signup_date,"last_login"=>$signup_date,"act_code"=>$act_code,"activated"=>"0"); 
    $id = $obj->insert_record("user_info",$user);
    if($id){
        echo "Record Inserted Sucessfully";
    }
}

?>