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

121
Views
Change the value of aobject based on other array of object value

I have below kind of object

sampleObject = {name : 'John' , age : 34 }

I want to update the age value based on the below array of object value:

sampleArrayOfObject = [{name:'John',age:20},{name:'Mathew',age:23},{name:'Mohammed',age:20}]

The final Output that I want is

updatedOject = {name:'John',age:20}
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

const sampleObject = {name : 'John', age : 34 }
const sampleArrayOfObject = [{name:'John',age:20}]
const updatedOject = {...sampleObject, age: sampleArrayOfObject[0].age}
about 4 years ago · Juan Pablo Isaza Report

0

I'm not exactly sure how you want the operation to be done, but here is one of the options:

function update(obj, objs) {
  return {
    ...obj,
    age: objs.find(v => v.name === obj.name)?.age ?? obj.age,
  };
}

let updatedOject = update(sampleObject, sampleArrayOfObject);

Here is playground for this option, and here is what you get when if you click "Run":

{
  "name": "John",
  "age": 20
} 

Here is the same option but with proper typings:

type Person = { name: string; age: number }

function update(obj: Person, objs: Person[]): Person {
  return {
    ...obj,
    age: objs.find(v => v.name === obj.name)?.age ?? obj.age,
  };
};

And this is the same code but with generics (I'd say a preferred approach, but don't take this for granted):

function update<T extends { name: string; age: number }>(obj: T, objs: T[]): T {
  return {
    ...obj,
    age: objs.find(v => v.name === obj.name)?.age ?? obj.age,
  };
};
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!