ES6语法,用underscore.js库
题目
假定我有对象
let obj = {
1: {
vegetables: ['banana', 'peach']
},
2: {
vegetables: ['pear', 'grapefruit']
}
};12345678
想将其变成
let obj = {
1: {
fruit: {
'banana': true,
'peach': true
}
},
2: {
fruit: {
'pear': true,
'grapefruit': true
}
}
};1234567891011121314
思路
先变key名,再在新key名所带的list对象将值变为新的字典对象的key
痛点
1.变Key名的语法
Object.defineProperty(obj, ‘newKeyName’, Object.getOwnPropertyDescriptor(obj, ‘oldKeyName’));1
2.既然是由list对象变为字典对象,一定会有obj.newKeyName = {}
这一出
3.旧的Key别忘了删除哦!
解题
_.each(obj, (item) => {
Object.defineProperty(item, 'fruit', Object.getOwnPropertyDescriptor(item, 'vegetables'));
item.fruit = {}; /*attach a new object to the new key name cuz this new obj will be a dictionary type soon*/
_.each(item.vegetables, (data) => {
item.fruit[data] = true;
}); /*for each value under the old key, I wanna set such value as the key for the dictionary attached to the new keyname*/
delete item.vegetables;
});123456789
Output is :
{"1":{"fruit":{"banana":true,"peach":true}},"2":{"fruit":{"pear":true,"grapefruit":true}}}1
思考
您有更简便的方法吗?