鍍金池/ 問答/HTML/ JavaScript對象合并問題

JavaScript對象合并問題

clipboard.png

最后想要的結(jié)果希望是這個(gè)樣子的。

let obj = {

title:{
    text: 'PIE',
    textStyle: {
      color: '#cccccc',
      fontSize:  45,
      fontWeight: 'normal',
      fontFamily: '華文細(xì)黑',
    },
    x: 'center',
    y: 'center'
}

}
就是b中的對象的值覆蓋掉a中的。

回答
編輯回答
法克魷

//最外面for循環(huán)依情況加.

for(key in b.title){
    a.title.text = b.title.text;
        for(k in b.title.textStyle){
            a.title.textStyle[k] =  b.title.textStyle[k];
        }
}
2018年3月1日 06:12
編輯回答
情皺
2017年10月23日 20:19
編輯回答
茍活

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

2017年2月14日 13:40
編輯回答
尐懶貓

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

2018年2月12日 21:44
編輯回答
心上人

原生js 寫的

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

merge(a,b)
2018年8月14日 13:23
編輯回答
蔚藍(lán)色

可以自己寫深度復(fù)制,不過我建議用成熟的庫,比如 lodash,那么這里從左至右深度復(fù)制建議用 defaultsDeep

import {defaultsDeep} from 'lodash';

let obj = defaultsDeep(b, a); // 注意從左至右
2018年2月8日 01:20
編輯回答
葬憶

試試這個(gè):var obj = $.extend(true, a, b);

語法:jQuery.extend( [deep ], target, object1 [, objectN ] )
深淺拷貝對應(yīng)的參數(shù)就是[deep],是可選的,為true或false。默認(rèn)情況是false(淺拷貝),并且false是不能夠顯示的寫出來的。如果想寫,只能寫true(深拷貝)

2017年8月26日 00:07
編輯回答
怪痞
var a = {
  title: {
    text: '餅圖',
    textStyle: {
      color: '#ffffff',
      fontSize: 45,
      fontWeight: 'normal',
      fontFamily: '華文細(xì)黑'
    },
    x: 'center',
    y: 'center'
  }
}

var b = {
  title: {
    text: 'PIE',
    textStyle: {
      color: '#cccccc'
    }
  },
  test: 'test'
}

function merge(target, source) {
  for (key in source) {
    if (target.hasOwnProperty(key) && typeof target[key] === 'object') {
      merge(target[key], source[key])
    } else {
      target[key] = source[key]
    }
  }
}

merge(a, b)

console.log(a)
2018年8月4日 06:54