Home > Net >  Merge two object arrays by matching partial value
Merge two object arrays by matching partial value

Time:11-04

I have two objects of arrays like the below:

person: {
    0: {
        firstName: John
        lastName: Doe
        avatar: https://sitename.com/filename.jpg
    },
    etc..
}
image: {
    0: {
        Key: filename.jpg
        files: {
            srcSet: 'filename.jpg 256w'
        }
    }
}

My goal is to match the objects up via the value found in avatar with the value in Key, and after matching merge the objects of arrays into a new array structure like the below:

person: {
    0: {
        firstName: John
        lastName: Doe
        avatar: https://sitename.com/filename.jpg
        Key: filename.jpg
        files: {
            srcSet: 'filename.jpg 256w'
        }
    },
    etc..
}

My gut tells me some sort of .filter and .map chained to the filter could help create the new array of objects, however, am unsure how to match a partial value.

CodePudding user response:

You can't use map over objects, but you can use Object.values(object) to get its values

const person = {
    0: {
        firstName: "John",
        lastName: "Doe",
        avatar: "https://sitename.com/filename.jpg"
    },
}
const image = {
    0: {
        Key: "filename.jpg",
        files: {
            srcSet: 'filename.jpg 256w'
        }
    }
}

const getPersonImageKey = (person) => {
  return person.avatar.split("/").at(-1);
}

const mergedObjs = Object.values(person).map(person => {
  const relatedImage = Object.values(image).find(image => image.Key === getPersonImageKey(person));
  return {...person, ...relatedImage};
})

const finalObj = {};
mergedObjs.forEach((obj, idx) => finalObj[idx] = obj); 

console.log(finalObj);
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

You can do something like this by calling Array.prototype.map() on Object.values(yourobject)

After calling map on values of the original object, you can check if an element with the same key exists in your second object, if it does use the spread operator to create a new resultant object with the combined properties and then return it

const person = {
    0: {
        firstName: "John",
        lastName: "Doe",
        avatar: "https://sitename.com/filename.jpg"
    },
}
const image = {
    0: {
        Key: "filename.jpg",
        files: {
            srcSet: 'filename.jpg 256w'
        }
    }
}

const imageKey = (avatar) => {
    const arr = avatar.split('/');
    return arr[arr.length - 1];
}

const val = Object.values(person).map(v => {
    const found = Object.values(image).find(x => x.Key == imageKey(v.avatar));
    if (found) 
        return {...v, ...found };
    else 
        return {...v}
})

console.log(val);
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related