Home > Blockchain >  create new object value based on another object id
create new object value based on another object id

Time:11-05

I need to update (or create new array) the id value in obj1 based on the id value in obj2. What is the best way to do this? I've tried with map and reduce but I wasn't successful. Any help will be appreciated.

const obj1 = [ { id: 1, name: 'foo' }, { id: 2, name: 'bar' } ]

const obj2 = { A: { id: 1, externalId:'AAA' }, B: { id: 2, externalId:'BBB' } }

outputExpected: [ { id: 'AAA', name: 'foo' }, { id: 'BBB', name: 'bar' } ]

CodePudding user response:

Depending on the size of your arrays it may be more efficient to build a Map indexing obj2 ids (Map(2) { 1 => 'AAA', 2 => 'BBB', ... }) which can be used in mapping obj1.

const obj1 = [{ id: 1, name: 'foo' }, { id: 2, name: 'bar' },];
const obj2 = { A: { id: 1, externalId: 'AAA' }, B: { id: 2, externalId: 'BBB' } };

const map = new Map(Object.values(obj2).map((o) => [o.id, o.externalId]));

const result = obj1.map(({ id, ...o }) => ({ id: map.get(id), ...o }));

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

CodePudding user response:

I'd suggest using Array.map(), searching obj2 for a matching id in each object in obj1, we'd use Array.find() to get the corresponding value in obj2.

const obj1 = [ { id: 1, name: 'foo' }, { id: 2, name: 'bar' } ]
const obj2 = { A: { id: 1, externalId:'AAA' }, B: { id: 2, externalId:'BBB' } }


const result = obj1.map((obj) => { 
    const match = Object.values(obj2).find(el => el.id === obj.id);
    return { id: match.externalId, name: obj.name };
});

console.log('Result:', result)
.as-console-wrapper { max-height: 100% !important; top: 0; }
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

Array.map works. Read values of obj2 as array to map to expected result. I suppose object keys A, B could be ignored.

const obj1 = [ { id: 1, name: 'foo' }, { id: 2, name: 'bar' } ];
const obj2 = { A: { id: 1, externalId:'AAA' }, B: { id: 2, externalId:'BBB' } };

const result = Object.values(obj2).map(({id, externalId}) => ({
    id: externalId, name: obj1.find(item => item.id === id)?.name
}));

console.log(JSON.stringify(result));
<iframe name="sif3" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related