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}
const sampleObject = {name : 'John', age : 34 }
const sampleArrayOfObject = [{name:'John',age:20}]
const updatedOject = {...sampleObject, age: sampleArrayOfObject[0].age}
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,
};
};