This article mainly introduces the Object value merging method in JavaScript in detail. It has certain reference value. Interested friends can refer to it. I hope it can help everyone.
Foreword: In daily development work, we may encounter the copying of all values in objects in js, or we may develop clients through electron, and face the merge of settings when revising. question. So this article will give a brief solution to this problem.
Introduction: For example, if there are obj1 and obj2, we need to copy all the values in obj1 with the same field and the same depth in obj2 to obj2, and we need to keep the field structure of obj2 unchanged, just call the method (using ES6 writing method).
Code:
/** * 将src中的数据copy到dist中,并保留dist的结构 * @param src * @param dist */ copyValue(src, dist) { if (!src || typeof(src) !== 'object' || typeof(dist) !== 'object'){ return ; } let keys = Object.keys(dist) if (keys && keys.length > 0 && isNaN(keys[0])){ keys.forEach(key => { let value = dist[key] let srcVal = src[key] // 判断是不是对象,如果是则继续遍历,不是则开始赋值或忽略 if (value !== undefined && typeof(value) === 'object' && srcVal && typeof(srcVal) === 'object' && srcVal[0] === undefined){ copyValue(srcVal, value) } else if (value !== undefined && srcVal && typeof(value) == typeof (srcVal)){ // 如果源数据存在,并且类型一致,则开始赋值 dist[key] = src[key] } }) } },
Related recommendations:
Detailed explanation of the use of two methods in regular and object in Java
Detailed explanation of usage examples of object.extend static method in Javascript
Interpretation of Object and param attributes in html
The above is the detailed content of Detailed explanation about Object value merging method in JavaScript. For more information, please follow other related articles on the PHP Chinese website!