Javascript 使用lodash变换嵌套对象
输入:Javascript 使用lodash变换嵌套对象,javascript,lodash,Javascript,Lodash,输入: const a = { "8": [{ "strategy": 123, "id": 1, "config": { "global_dag_conf": { "algo_v2_conf": { "features_to_com
const a = {
"8": [{
"strategy": 123,
"id": 1,
"config": {
"global_dag_conf": {
"algo_v2_conf": {
"features_to_combine": [],
"segments": [],
"force_performance": false,
"min_bid": 0,
"max_bid": 13
}
}
}
}],
"13": [{
"strategy": 456,
"id": 2,
"config": {
"global_dag_conf": {
"algo_v2_conf": {
"ivr_measured": []
}
}
}
}]
}
输出:
{
"8": [
{
"global_dag_conf": {
"algo_v2_conf": {
"features_to_combine": [],
"segments": [],
"force_performance": false,
"min_bid": 0,
"max_bid": 13
}
},
"algo_id": 1
}
],
"13": [
{
"global_dag_conf": {
"algo_v2_conf": {
"ivr_measured": []
}
},
"algo_id": 2
}
]
}
我尝试了下面的解决方案,效果很好,但需要知道是否有更好的方法使用lodash和JS来实现这一点
result = _.map(_.keys(addtionalAlgos), (algoType) => {
addtionalAlgos[algoType] = _.map(addtionalAlgos[algoType], v => _.assign(v.config, { algo_id: v.id }));
return addtionalAlgos;
})[0]
用于迭代键,并使用和重新格式化对象:
const data={“8”:[{“策略”:123,“id”:1,“配置”:{“全局报价”:456,“id”:2,“配置”:{“全局报价”:456,“id”:2,“配置”:{“全局报价”:{“全局报价”:{”
const result=\映射值(数据,
arr=>arr.map({id:algou-id,config})=>
({algou_id,…config})
))
console.log(结果)
不含lodash的替代品
函数reduce
允许生成一个对象,该对象将使用函数map
填充,该函数将原始对象转换为所需结构
const a={“8”:[{“策略”:123,“id”:1,“配置”:{“全局配置”:{“算法v2配置”:{“功能到组合”:[],“分段”:[],“强制性能”:false,“最小出价”:0,“最大出价”:13}}}],“13”:[{“策略”:456,“id”:2,“配置”:{“全局出价”:{“算法v2}:{“ivr_测量”:[]}}}};
让result=Object.entries(a).reduce((a,[key,arr])=>{
返回Object.assign(a,{[key]:arr.map({id:algo_id,config})=>({algo_id,…config}));
},Object.create(null));
控制台日志(结果)代码>
.as控制台包装{max height:100%!important;top:0;}
这里有一个不使用lodash的解决方案:
- 用于获取键值对数组
- 通过在阵列上使用创建新对象
- 用于创建新的对象数组李>
- 分解每个对象以获取
id
和config
。config
变量以删除一级嵌套
const-input={“8”:[{“策略”:123,“id”:1,“配置”:{“全局报价”:456,“id”:2,“配置”:{“全局报价”:456,“id”:2,“配置”:{“全局报价”:{“全局报价”:{”
常量输出=
Object.entries(输入)
.reduce((r[键,值])=>{
r[key]=value.map(({id,config})=>({algo_id:id,…config}));
返回r;
}, {})
console.log(输出)
使用、和方法的纯Lodash解决方案
let data={“8”:[{“strategy”:123,“id”:1,“config”:{“global_dag_conf”:{“algou v2_conf”:{“features to_combine”:[],“segments”:[],“force_performance”:false,“min_bid”:0,“max_bid”:13}],“13”:[{“strategy 456 id”:2,“config”:{“global__dag_conf;
让res=\.mapValues(数据,arr=>\.map(arr,obj=>\.assign({
'算法id':对象id,
'global_dag_conf':obj.config.global_dag_conf
})));
控制台日志(res)代码>
输入和输出之间的关系是什么?