简体   繁体   中英

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):

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.

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.

 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) 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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