Home > front end >  How to combine my array and json result in one?
How to combine my array and json result in one?

Time:09-26

I want to combine two json results, but im struggling getting it done..

first one (galleryData):

[
      { "userId": 2, "profile": { "profileImage": "image" } },
      { "userId": 4, "profile": { "profileImage": "image" } },
]

second one (combinations):

{
  data: [
    { round: 1, partner: 2 },
    { round: 2, partner: 4 }
  ]
}

the output im expecting:

{
  data: [
    { round: 1, userId: 2, "profile": { "profileImage": "image" } },
    { round: 2, userId: 4, "profile": { "profileImage": "image" } }
  ]
}

Basically I need the profileImage from one of my result and map it to the correct user id

What I tried so far with no success:

let combinedResult = galleryData["userId"].map((item, i) => Object.assign({}, item, combinations[i]));

CodePudding user response:

You can use map and on each callback use find to find the corresponding userId === partner

const galleryData = [
      { "userId": 2, "profile": { "profileImage": "image" } },
      { "userId": 4, "profile": { "profileImage": "image" } },
]

const combinations = {
  data: [
    { round: 1, partner: 2 },
    { round: 2, partner: 4 }
  ]
}

let combinedResult = { 
  data: galleryData.map((item, i) => {
    let combination = combinations.data.find(c => c.partner === item.userId);
    return { ...item, round: combination.round } 
  })
};

console.log(combinedResult)

CodePudding user response:

I think a little try using Array.forEach and then merge the Objects

a = [
          { "userId": 2, "profile": { "profileImage": "image" } },
          { "userId": 4, "profile": { "profileImage": "image" } },
    ]
    
        b = {
          data: [
            { round: 1, partner: 2 },
            { round: 2, partner: 4 }
          ]
        }
// inside forEach you can write the logic to get elements from array 'a' as you can use `find` to check which user is needed 
    
        b.data.forEach((i,e) => { b.data[e] = {...i, ...a[e]} })

console.log(b)

CodePudding user response:

Hope it will be helpful.

let galleryData = [
      { "userId": 2, "profile": { "profileImage": "image" } },
      { "userId": 4, "profile": { "profileImage": "image" } },
];
let galleryDataAsUserId = {};
galleryData.forEach(elem=>{
    galleryDataAsUserId[elem.userId] = elem;
})
let combinations = {
  data: [
    { round: 1, partner: 2 },
    { round: 2, partner: 4 }
  ]
};
let data = combinations.data;
data.map(elem=>{
    let newElem = elem;
    newElem.profile = galleryDataAsUserId[elem.partner].profile;
});
console.log(data)

  • Related