function assign(target: Record<string, Object>, ...source: Object[]): Record<string, Object> {
for (const items of source) {
for (const key of Object.keys(items)) {
target[key] = Reflect.get(items, key);
}
}
return target;
}
function jsonMerge() {
let jsonText1 = '{"aa": "aa", "bb": {"aa": "aaa"}, "cc": "cc"}';
let jsonText2 = '{"dd": "dd", "ee": 3, "ff": "ff", "cc": "ccc"}';
let jsonRecord1: Record<string, object> = JSON.parse(jsonText1) as Record<string, object>;
let jsonRecord2: Record<string, object> = JSON.parse(jsonText2) as Record<string, object>;
const multiObjectMerged = assign(jsonRecord1, jsonRecord2);
console.info('jsonMerge', JSON.stringify(multiObjectMerged));
}
@Entry
@Component
struct JsonMergeDemo {
build() {
Column({ space: 16 }) {
Button('合并测试').onClick(() => {
jsonMerge();
});
}.width('100%').height('100%')
.justifyContent(FlexAlign.Center);
}
} export class ObjectUtil {
static Assign<T extends object, U>(target: T, source: U): T & U {
// 1、使用Object.assign()
return Object.assign(target, source);
// 2、使用扩展运算符
return { ...target, ...source };
}
} import { ObjectUtil } from './ObjectUtil';
function jsonMerge() {
let jsonText1 = '{"aa": "aa", "bb": {"aa": "aaa"}, "cc": "cc"}';
let jsonText2 = '{"dd": "dd", "ee": 3, "ff": "ff", "cc": "ccc"}';
let jsonRecord1: Record<string, object> = JSON.parse(jsonText1) as Record<string, object>;
let jsonRecord2: Record<string, object> = JSON.parse(jsonText2) as Record<string, object>;
const multiObjectMerged = ObjectUtil.Assign(jsonRecord1, jsonRecord2);
console.info('jsonMerge', JSON.stringify(multiObjectMerged));
} 合并后的数据为:{"aa":"aa","bb":{"aa":"aaa"},"cc":"ccc","dd":"dd","ee":3,"ff":"ff"}。前一个JSON中键值对{"cc":"cc"}被后一个JSON中key值相同的{"cc":"ccc"}覆盖。