我具有如下结构-
var a = {
foo: {
dates: {'2018-11-29': 2020.55},
strategies: [
{
expiryDate: '2018-11-29',
projects: [
{
expiryDate: '2018-11-29',
name: 'foo',
value: 500
}
]
}
]
},
bar: {
dates: {'2018-11-29': 2020.55},
strategies: [
{
expiryDate: '2018-11-29',
projects: [
{
expiryDate: '2018-11-22',
name: 'bar',
value: 650
},
{
expiryDate: '2018-11-22',
name: 'mario',
value: 700
}
]
}
]
}
}
我正在尝试找到一种方法,可以使用lodash轻松更新内部projects
集合。但是我遇到了错误
我正在尝试做这样的事情
const finalTransformedData = _.mapValues(
a,
(value, key) => {
value.strategies.map(strats =>
strats.projects.map(trade =>
Object.assign(
{},
{ trade: 1 },
),
),
);
},
);
但是我得到以下输出-我在哪里错了?
{ foo: undefined, bar: undefined }
上面的示例代码有点过分简化,但是我要寻找的是以某种方式轻松地操作项目数组中的对象-本质上是这样的-通过遍历对象并分配新的对象来替换数组中的对象对象(从object.assign获取)
foo: {
dates: {'2018-11-29': 2020.55},
strategies: [
{
expiryDate: '2018-11-29',
projects: [
{
trade: 1
}
]
}
]
},
bar: {
dates: {'2018-11-29': 2020.55},
strategies: [
{
expiryDate: '2018-11-29',
projects: [
{
trade: 1
},
{
trade: 1
}
]
}
]
}
答案 0 :(得分:2)
如果没有lodash
,您也可以尝试循环for..of
var a = { foo: { dates: {'2018-11-29': 2020.55}, strategies: [ { expiryDate: '2018-11-29', projects: [ { expiryDate: '2018-11-29', name: 'foo', value: 500 } ] } ] }, bar: { dates: {'2018-11-29': 2020.55}, strategies: [ { expiryDate: '2018-11-29', projects: [ { expiryDate: '2018-11-22', name: 'bar', value: 650 }, { expiryDate: '2018-11-22', name: 'mario', value: 700 } ] } ] }}
for(let { strategies } of Object.values(a)) {
for(let s of strategies) {
s.projects = s.projects.map(d => ({ trade: 1 }))
}
}
console.log(a)
答案 1 :(得分:1)
请勿为此使用lodash
。而是使用immer
-https://github.com/mweststrate/immer
您可以这样做:
const finalTransformedData = produce(
a,
(draft) =>
draft.strategies.forEach(strats =>
strats.projects.forEach(project => {
project.trade = 1
})
),
);