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

博客围绕ES6语法结合underscore.js库展开。给出题目,即对对象进行转换。阐述思路,先变key名,再将list对象值变为新字典对象的key。指出痛点,如变key名语法等。最后给出解题结果,并思考是否有更简便方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

思考

您有更简便的方法吗?

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值