我有一个看起来像这样的对象:
let data = {
color: "green",
color1: "red",
color2: null,
color3: 34,
color4: null,
color5: true,
color6: [],
}
我想只提取具有值的属性并创建一个新对象。所以这个新对象看起来像这样:
let data = {
color: "green",
color1: "red",
color3: 34,
color5: true,
}
这将是动态的,属性和值可以改变,但最后我总是想做一个只有值的对象。有什么实际可行的方法呢?
答案 0 :(得分:1)
您可以按照以下步骤创建Object.keys
:
Array.reduce
acc
将键数组转换为转换后的对象。curr
中,您将获得累积的对象。isEmptyObject
中,您将收到当前密钥null
,您可以在其中定义规则以检查是否存在。根据您的示例,我检查了Array length
和let data = {
color: "green",
color1: "red",
color2: null,
color3: 34,
color4: null,
color5: true,
color6: [],
}
var newObj = Object.keys(data).reduce((acc, curr) => {
if (isEmptyObject(data, curr)) return acc;
acc[curr] = data[curr];
return acc;
}, {});
function isEmptyObject(obj, key) {
return obj[key] === null || Array.isArray(obj[key]) && obj[key].length === 0;
}
console.log(newObj);
。您可以修改此功能。
<?php
include ("dbConnect.php");
require 'libPassword.php';
function filter_email_header($email){
return preg_replace('/[\0\n\r\|\!\/\<\>\^\$\%\*\&]+/','',$email);
}
if(isset($_POST['submit'])){
$forename = $_POST['forename'];
$surname = $_POST['surname'];
$telephone = $_POST['telephone'];
$address = $_POST['address'];
$medical_conditions = $_POST['medical_conditions'];
$dob = $_POST['dob'];
$email = $_POST['email'];
$password = $_POST['password'];
$last_login = date("Y-n-d");
$dbQuery=$db->prepare("SELECT email FROM customer where email > 0");
$dbParams = array('email'=>$email);
$dbQuery->execute($dbParams);
if ($dbQuery) {
$message = "username already exists";
echo "<script type='text/javascript'>alert('$message');</script>";
}//if
else{
$hashPassword = password_hash($pass, PASSWORD_BCRYPT, array("cost" => 12));
if($dbQuery->rowCount()==0){
$dbQuery=$db->prepare("INSERT INTO customer (forename, surname, telephone, address, medical_conditions, dob, email, password) VALUES (:forename, :surname, :telephone, :address, :medical_conditions, :dob, :email, :hashPassword)");
$dbParams = array('forename'=>$forename,'surname'=>$surname, 'telephone'=>$telephone, 'address'=>$address,'medical_conditions'=>$medical_conditions, 'dob'=>$dob, 'email'=>$email, 'hashPassword'=>$hashPassword);
$dbQuery->execute($dbParams);
if($dbQuery) {
header("Location: myProfile.php");
}//if
}//if
else{
echo('Please fill out all fields marked with *');
}//else2
}//else1
if(isset($email)){
$sender='jess@gymmembership.com';
$email = filter_email_header($email);
$headers = "From:". $sender;
$to = $email; // Send email to our user
$subject = 'Signup | Verification'; // Give the email a subject
$message = '
Thanks for signing up!
Here is your login details:
------------------------
Your email: '.$email.'
Password: '.$password.'
------------------------
You can now login to your account:
'; // Our message above including the link
$headers = 'From:gymmanagementsystem' . "\r\n"; // Set from headers
//mail($to, $subject, $message, $headers); // Send our email
$sent=mail($to, $subject, $message, $email);
}}
?>
&#13;