我正在遍历具有设置为array的属性的对象,然后按以下方式使用它:
let merged= [];
for (let sup of superObject) {
let sname = sup.superObjectName;
for (let sub of sup.subObject) {
merged.push({superObject: sname, subObject: sub.subObjectName})
}
}
现在上面的代码可以工作并完成工作,但是我认为可以使用Lodash进行改进,但我无法使其工作。我尝试以几种不同的方式使用flatMap
,但似乎都无法正常工作,而在功能方面朝着正确方向发展的人似乎根本没有改进。
有什么想法吗?
更新:
superObject
示例:
{
superObjectName: "someName",
subObject: [
{subObjectName: "someSubName"},
{subObjectName: "someSubName2"}
]
}
答案 0 :(得分:3)
这与您的代码相同:
const merged = _.flatMap(superObject, ({superObjectName, subObject}) =>
_.map(subObject, ({subObjectName}) => ({
superObject: superObjectName,
subObject: subObjectName
}))
);
superObject
中的每个值都用map
转换为Array,然后在flatMap
内展平。
答案 1 :(得分:2)
您可以使用flatMap,使用lodash获取道具并获得所需的结果。
var data= [{
superObjectName: "someName",
subObject: [
{subObjectName: "someSubName"},
{subObjectName: "someSubName2"}
]
}];
const result = _.flatMap(data, ({ superObjectName, subObject}) =>
_.map(subObject, ({subObjectName})=> ({superObject: superObjectName, subObject: subObjectName}))
);
console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.js"></script>