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

时间:2018-12-24 21:55:19

标签: javascript arrays object

对不起,标题令人困惑,我遇到了3个动态数组(可以为空)的问题:

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

我需要将它们更改为:

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

我试图解决这个问题:

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 } });

但可悲的是,这会覆盖每张地图的newState。

2 个答案:

答案 0 :(得分:1)

如果将输入存储为对象,属性名称就是变量名称,那么这是一种处理方法:

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

这允许您进行其他配置,在这些配置中您可以合并三个以上的阵列,并且名称可能不同。

答案 1 :(得分:0)

可以通过这种方式解决,因为对于性能要求不高的代码,我发现使用了地图清洁器。

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)