Lodash 从对象数组中减少对象数组
Lodash reduce array of objects from array of objects
我正在尝试通过
获取所有部分中所有指南场景的列表
let combinedScenes = _.reduce(sections,
(prev, section) => {return {...prev, ...section.guideScenes}},
{}
)
它只返回第一部分列表,我如何将所有部分都放在那里?
const sections = [{guideScenes: ['hello']}, {guideScenes: ['world']}, {guideScenes: ['hi', 'yo']}]
let combinedScenesObj = _.reduce(sections, (prev, section, index) => {
return {...prev, [index]: [...section.guideScenes]}
}, {})
console.log('object:', combinedScenesObj)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.5/lodash.core.js"></script>
你很接近你需要一个键被添加到每个数组,因为你试图添加到一个对象
//dummy data
const sections = [{guideScenes: ['hello']}, {guideScenes: ['world']}, {guideScenes: ['hi', 'yo']}]
如果你想解析一个对象,你应该给这个项目一个键,例如,我在这个例子中使用了索引
let combinedScenesObj = _.reduce(sections, (prev, section, index) => {
return {...prev, [index]:[...section.guideScenes]};
}, {})
// { 0: ["hello"], 1: ["world"], 2: ["hi", "yo"] }
我正在尝试通过
获取所有部分中所有指南场景的列表let combinedScenes = _.reduce(sections,
(prev, section) => {return {...prev, ...section.guideScenes}},
{}
)
它只返回第一部分列表,我如何将所有部分都放在那里?
const sections = [{guideScenes: ['hello']}, {guideScenes: ['world']}, {guideScenes: ['hi', 'yo']}]
let combinedScenesObj = _.reduce(sections, (prev, section, index) => {
return {...prev, [index]: [...section.guideScenes]}
}, {})
console.log('object:', combinedScenesObj)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.5/lodash.core.js"></script>
你很接近你需要一个键被添加到每个数组,因为你试图添加到一个对象
//dummy data
const sections = [{guideScenes: ['hello']}, {guideScenes: ['world']}, {guideScenes: ['hi', 'yo']}]
如果你想解析一个对象,你应该给这个项目一个键,例如,我在这个例子中使用了索引
let combinedScenesObj = _.reduce(sections, (prev, section, index) => {
return {...prev, [index]:[...section.guideScenes]};
}, {})
// { 0: ["hello"], 1: ["world"], 2: ["hi", "yo"] }