JS基础 改对象中的Key名,变数组中的值为新的字典型中的Key

来源:互联网 发布:mysql引擎区别 编辑:程序博客网 时间:2024/06/03 16:56

ES6语法,用underscore.js库

题目

假定我有对象

let obj = {    1: {        vegetables: ['banana', 'peach']    },    2: {        vegetables: ['pear', 'grapefruit']      }};

想将其变成

let obj = {    1: {        fruit: {            'banana': true,             'peach': true        }    },    2: {        fruit: {            'pear': true,             'grapefruit': true        }       }};

思路

先变key名,再在新key名所带的list对象将值变为新的字典对象的key

痛点

1.变Key名的语法

Object.defineProperty(obj, ‘newKeyName’, Object.getOwnPropertyDescriptor(obj, ‘oldKeyName’));

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;});

Output is :

{"1":{"fruit":{"banana":true,"peach":true}},"2":{"fruit":{"pear":true,"grapefruit":true}}}

思考

您有更简便的方法吗?

原创粉丝点击