给对象添加新字段

206 阅读1分钟

普通对象

var myInfo = {

"name":"tonny",

"qq":"11111111", 

};

//给myInfo增加一个id字段

myInfo.id = "123";

console.log("1-普通增加",myInfo);

结果:

嵌套对象

var classInfo = {
    "张三":{
        班级:'a班'
    },
    "李四":{
        班级:'c班'
    }
};

var detailInfo={
    "张三学号":1,
    "李四学号":2
}

将detailInfo 加入到 classInfo 里

_.forOwn(classInfo, ($class, type) => {
    _.forOwn(detailInfo, (detail, key) => {
        //判断学号是张三的还是李四的
    	if (key.indexOf(type) >= 0) {
    	    //张三学号 -》学号
    	    let $key = _.split(key, type)[1];
    	    classInfo[type][$key] = detail;
    	}
    });
});

console.dir(classInfo);

结果:

多层嵌套:

let InfoMap = {
    textInfo: {
    	text1: {},
    	text2: {}
    },
    pricesInfo: {
    	price1: {},
    	price2: {},
    	price3: {}
    }
};

let Infos={
    "price1value1": 'price1value1',
    "price1value2": 'price1value2',
    "price2value1": 3,
    "price2value2": 40,
    "price3value1": 15,
    "price3value2": 78,
    "text1value1": "text1value1",
    "text1value2": "text1value2",
    "text2value1": "text2value1",
    "text2value2": null
    }

_.forOwn(InfoMap, (map, type) => {
    _.forOwn(map, (value, name) => {
    	_.forOwn(Infos, (info, key) => {
    		if (key.indexOf(name) >= 0) {
    			let text = _.split(key, name)[1];
    			map[name][text] = info;
    		}
    	});
    });
});

结果:

普通对象的来源链接:www.cnblogs.com/mywangpinga…