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}}}
思考
您有更简便的方法吗?
阅读全文
0 0
- JS基础 改对象中的Key名,变数组中的值为新的字典型中的Key
- java.util.HashMap中的key为对象的问题,对象key获得相应的value值
- js判断数组或对象中的key是否存在
- 替换python字典中的key值
- 如何自定义字典中的key
- js中的变量作为json的key
- delphi中的key值
- python判断字典中的key是否存在
- 迭代字典中的key和value
- HashMap中的key为什么不能为可变对象
- 五三、提取浏览器 url 中的参数名和参数值,生成一个key/value 的对象
- iOS应用启动launchOptions字典中的key值
- JS(JQEERY) 获取JSON对象中的KEY VALUE
- JS(JQEERY) 获取JSON对象中的KEY VALUE
- js对象中的key按照a-z排序
- JS获取JSON对象中的KEY和VALUE
- python 把文件中每列的第一个值作为字典中的key键值索引
- 得到json 中的key 值
- 昨日学习总结
- 欢迎使用CSDN-markdown编辑器
- SSH框架分页展示
- 有序的map LinkedHashMap
- Android官网内存管理概略--翻译
- JS基础 改对象中的Key名,变数组中的值为新的字典型中的Key
- Linux模式设计8-编译器检查 2011-11-25 18:53:58
- 水果消除 hnust bfs专题
- [转]SuspendLayout()用处
- 容器CNI完全解读calico实现(三)
- angularjs的$index序号
- JVM系列一:JVM内存组成及分配
- HDFS中dfs 命令
- VO(value object)