0

I am trying to merge two objects into one, but i need to makes sure that the first array of objects values and key become key values of another array of objects hopefully this makes sense:

So i have a dataConstant with some info like this:

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'
    }
]

I import this const into my React component. Inside the same I am importing multiple images and put them into array of objects like so:

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

the result of this is:

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"}

But I would like the first two element 0 and 1 to be inside of the 3 and 4

2
  • Did you mean var combi = [...logo, ...tileData];? Commented Jun 12, 2019 at 18:10
  • Hi John, just wrote you a solution, let me know if that helps. Commented Jun 12, 2019 at 18:34

1 Answer 1

7
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"}]

You can use .map() to combine the two arrays like so:

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

Results in:

(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)
Sign up to request clarification or add additional context in comments.

1 Comment

Awesome @John! Please consider marking this as the answer :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.