简体   繁体   English

将多个动态数组合并为单个对象数组

[英]Merge multiple dynamic arrays into a single array of objects

Sorry for the confusing title, I have a problem where I have 3 dynamic arrays (can be empty): 抱歉,标题令人困惑,我有一个问题,其中有3个动态数组(可以为空):

const titles = ["Title 1", "Title 2", "Title 3"]
const subtitles = ["Subtitle 1", "Subtitle 2"]
const contents = ["Content 1"]

and I need to change them into: 我需要将它们更改为:

const newArr = [
    { title: "Title 1", subtitle: "Subtitle 1", content: "Content 1" },
    { title: "Title 2", subtitle: "Subtitle 2" },
    { title: "Title 3" }
]

My attempt to solve this: 我试图解决这个问题:

const newState = []

titles.map((titleItem, index) => { newState[index] = { title: titleItem } });
subtitles.map((subtitleItem, index) => { newState[index] = { subtitle: subtitleItem } });
contents.map((contentItem, index) => { newState[index] = { content: contentItem } });

but sadly, this overwrites the newState for every map. 但是可悲的是,这将覆盖每个地图的newState。

If you would store the input as an object, where the property names are what you have as variable names, then here is one way to do it: 如果将输入存储为对象,属性名称就是变量名称,那么这是一种实现方法:

 function zip(arg) { return Object.entries(arg).reduce( (acc, [k, arr]) => { arr.forEach( (v, i) => (acc[i] = acc[i] || {})[k] = v ); return acc; }, []); } const result = zip({ title: ["Title 1", "Title 2", "Title 3"], subtitle: ["Subtitle 1", "Subtitle 2"], content: ["Content 1"] }); console.log(result); 

This allows for other configurations where you would have more than 3 arrays to merge, with potentially different names. 这样可以进行其他配置,在这些配置中,您可能要合并三个以上具有不同名称的阵列。

Could be solved this way, for not performance-critical code I find usage of maps cleaner. 可以通过这种方式解决,因为对于性能要求不高的代码,我发现使用了Maps Cleaner。

 let titles = ["Title 1", "Title 2", "Title 3"] let subtitles = ["Subtitle 1", "Subtitle 2"] let contents = ["Content 1"] const maxLength = Math.max(titles.length, subtitles.length, contents.length); const resultWithUndefined = Array(maxLength).fill(null) .map((_,i) => [titles[i], subtitles[i], contents[i]]) .map(([title, subtitle, content]) => ({title, subtitle, content})); console.log(resultWithUndefined) const resultClean = Array(maxLength).fill(null) .map((_,i) => [titles[i], subtitles[i], contents[i]]) .map(([title, subtitle, content]) => Object.assign({}, typeof title === "undefined" ? {} : {title}, typeof subtitle === "undefined" ? {} : {subtitle}, typeof content === "undefined" ? {} : {content}, )); console.log(resultClean) 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM