将对象数组插入另一个

时间:2019-06-12 18:01:18

标签: javascript

我正在尝试将两个对象合并为一个对象,但是我需要确保第一个对象值数组和键成为另一个对象数组的键值,希望这是有道理的:

所以我有一个dataConstant,其中包含以下信息:

export const tileData = [
    {
        title: 'JS CONS',
        skill: 40,
        visitTitle: 'Visit JS',
        visitUrl: 'https://www.google.co.uk'
    },
    {
        title: 'JS CONS',
        skill: 50,
        visitTitle: 'Visit JS',
        visitUrl: 'https://www.google.co.uk'
    }
]

我将此const导入我的React组件。在同一个内部,我将导入多个图像并将其放入对象数组,如下所示:

//the values of the objects keys are imported logos
getLogos(tileData) {
    const logo = [{logo: js}, {logo: react}];
    var combi = [...logo, ...i];
    console.log(combi);
    return combi;
}

其结果是:

0: {logo: "/static/media/js.a672e76f.png"}
1: {logo: "/static/media/react.5513eea1.png"}
2: {title: "JS CONS", skill: 40, visitTitle: "Visit JS", visitUrl: "https://www.google.co.uk"}
3: {title: "JS CONS", skill: 50, visitTitle: "Visit JS", visitUrl: "https://www.google.co.uk"}

但是我希望前两个元素0134

1 个答案:

答案 0 :(得分:6)

let logos = [{logo: "/static/media/js.a672e76f.png"},{logo: "/static/media/react.5513eea1.png"}]

let tileData = [{title: "JS CONS", skill: 40, visitTitle: "Visit JS", visitUrl: "https://www.google.co.uk"},{title: "JS CONS", skill: 50, visitTitle: "Visit JS", visitUrl: "https://www.google.co.uk"}]

您可以使用.map()像这样组合两个数组:

let combinedArr = logos.map((item, index) => {
    return {
    ...item,
    ...tileData[index]
    }
})

结果:

(2) [{…}, {…}]
0:
logo: "/static/media/js.a672e76f.png"
skill: 40
title: "JS CONS"
visitTitle: "Visit JS"
visitUrl: "https://www.google.co.uk"
__proto__: Object
1:
logo: "/static/media/react.5513eea1.png"
skill: 50
title: "JS CONS"
visitTitle: "Visit JS"
visitUrl: "https://www.google.co.uk"
__proto__: Object
length: 2
__proto__: Array(0)