Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

92
Views
create new object value based on another object id

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' } ]
about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

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);

about 4 years ago · Juan Pablo Isaza Report

0

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

about 4 years ago · Juan Pablo Isaza Report

0

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));

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!