JavaScript对象合并问题

https://img.mukewang.com/5c8b0e960001925903360528.jpg

最后想要的结果希望是这个样子的。


let obj = {


title:{

    text: 'PIE',

    textStyle: {

      color: '#cccccc',

      fontSize:  45,

      fontWeight: 'normal',

      fontFamily: '华文细黑',

    },

    x: 'center',

    y: 'center'

}

}

就是b中的对象的值覆盖掉a中的。


慕姐4208626
浏览 492回答 6
6回答

红颜莎娜

试试这个:var obj = $.extend(true, a, b);语法:jQuery.extend( [deep ], target, object1 [, objectN ] )深浅拷贝对应的参数就是[deep],是可选的,为true或false。默认情况是false(浅拷贝),并且false是不能够显示的写出来的。如果想写,只能写true(深拷贝)

叮当猫咪

原生js 写的function merge (target) {&nbsp; for (let i = 1, j = arguments.length; i < j; i++) {&nbsp; &nbsp; let source = arguments[i] || {};&nbsp; &nbsp; for (let prop in source) {&nbsp; &nbsp; &nbsp; if (source.hasOwnProperty(prop)) {&nbsp; &nbsp; &nbsp; &nbsp; let value = source[prop];&nbsp; &nbsp; &nbsp; &nbsp; if(typeof value === "object" ){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; target[prop] = merge(target[prop]||{},value)&nbsp; &nbsp; &nbsp; &nbsp; }else {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (value !== undefined) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; target[prop] = value;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; }&nbsp; return target;};merge(a,b)

RISEBY

{...a,...b},望采纳

泛舟湖上清波郎朗

Object.assign(a, b) ES6新语法

米琪卡哇伊

var a = {&nbsp; title: {&nbsp; &nbsp; text: '饼图',&nbsp; &nbsp; textStyle: {&nbsp; &nbsp; &nbsp; color: '#ffffff',&nbsp; &nbsp; &nbsp; fontSize: 45,&nbsp; &nbsp; &nbsp; fontWeight: 'normal',&nbsp; &nbsp; &nbsp; fontFamily: '华文细黑'&nbsp; &nbsp; },&nbsp; &nbsp; x: 'center',&nbsp; &nbsp; y: 'center'&nbsp; }}var b = {&nbsp; title: {&nbsp; &nbsp; text: 'PIE',&nbsp; &nbsp; textStyle: {&nbsp; &nbsp; &nbsp; color: '#cccccc'&nbsp; &nbsp; }&nbsp; },&nbsp; test: 'test'}function merge(target, source) {&nbsp; for (key in source) {&nbsp; &nbsp; if (target.hasOwnProperty(key) && typeof target[key] === 'object') {&nbsp; &nbsp; &nbsp; merge(target[key], source[key])&nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; target[key] = source[key]&nbsp; &nbsp; }&nbsp; }}merge(a, b)console.log(a)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript