2019/12/20

merge object

jQuery 有一個 $.extend 功能我覺得相當好用,假設你有兩個 object,{'name': 'chan', 'sport': 'basketball'},新的屬性是 {'sort': 'baseball'}, 透過 $.extend(object1, object2) 可以得到 {'name': 'chan', 'sport': 'baseball'},今天要在三個語言實現這個功能,但我要另外加一個內容是,如果新的內容是空字串就不覆蓋。

PHP
<?php  
  
$data = [  
    'name' => 'chan',  
    'sport' => 'basketball'  
];  
$newData = [  
    'name' => '',  
    'sport' => 'baseball'  
];  
$mergeObject = function($object1, $object2) {  
    return json_encode(  
        array_merge(  
            $object1,  
            array_filter(  
                $object2,  
                function($item) {  
                    return $item != '';  
                } 
            )  
        )  
    );  
}; 
  
echo $mergeObject($data, $newData); // {"name":"chan","sport":"baseball"}  
python
# coding=utf-8  
  
import json  
  
data = {  
    'name': 'chan',  
    'sport': 'basketball'  
}  
new_data = {  
    'name': '',  
    'sport': 'baseball'  
}  
  
  
def merge_object(object1, object2):  
    x = object1.copy()  
    n = {}
  
    for key, value in object2.items():  
        if value != '':  
            n[key] = value  
  
    x.update(n)  
  
    return json.dumps(x)  
  
  
print(merge_object(data, new_data)) # {"sport": "baseball", "name": "chan"}
node.js
let data = {  
    'name': 'chan',  
    'sport': 'basketball'  
};  
let newData = {  
    'name': '',  
    'sport': 'baseball'  
};  
let objectFilter = (object1, object2) => {  
    let n = {};  
  
    for (let i in object2) {  
        let value = object2[i];  
  
        if (value !== '') {  
            n[i] = value;  
        }  
    }  
  
    return JSON.stringify(Object.assign(object1, n));  
};  
  
console.log(objectFilter(data, newData)); // {"name":"chan","sport":"baseball"}

沒有留言: